john
john

Reputation: 1747

Get element by xpath on HTML string

I have a JS variable that contains an a string that represents an HTML page. For example:

var response = "<!DOCTYPE html><html><body><h1>This is heading 1</h1></body></html>"

I'd like to perform query selectors and xpath evaluations on this response to traverse through the HTML elements. Since the response is not in the DOM I can't use document.x actions.

One option is to write it into an invisible iframe in the DOM but this is not allowed for Chrome extensions. Are there any other alternatives?

Upvotes: 1

Views: 1265

Answers (2)

marcos
marcos

Reputation: 4510

You can use DOMparser to achieve that for example:

const response = "<!DOCTYPE html><html><body><h1>This is heading 1</h1></body></html>"
const parser = new DOMParser();
const parsedHtml = parser.parseFromString(response, 'text/html');

And process it as normal DOM components.

Upvotes: 3

Rajan
Rajan

Reputation: 1497

Use can use DOMParser

var response = "<!DOCTYPE html><html><body><h1>This is heading 1</h1></body></html>";
var dom = new DOMParser().parseFromString(response, 'text/html');
// Example
console.log(dom.querySelector('h1').textContent);

Upvotes: 3

Related Questions