Chris_F
Chris_F

Reputation: 5567

Is it possible to supply a baseURI when using DOMParser.parseFromString?

I am using DOMParser to parse a document that contains relative URLs for things like the action property of a form. Because the baseURI of the document created by DOMParser is null accessing the action property yields a blank string. I can get around this by using getAttribute but if it is possible to specify a baseURI when using DOMParser that would be ideal.

Upvotes: 9

Views: 543

Answers (1)

customcommander
customcommander

Reputation: 18961

Rather than injecting a <base> in the HTML before parsing, have you considered doing something similar after parsing?

function parse(baseUri, htmlStr) {
    var doc = (new DOMParser).parseFromString(htmlStr, 'text/html');
    var base = doc.createElement('base');
    base.href = baseUri;
    doc.head.appendChild(base);
    return doc;
}

var parsedDoc = parse('http://example.com', '<form action="/index.html"></form>');

console.log(

    parsedDoc.querySelector('form').action

)

Upvotes: 6

Related Questions