1

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?

john
  • 1,561
  • 3
  • 20
  • 44

2 Answers2

3

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.

marcos
  • 4,473
  • 1
  • 10
  • 24
3

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);
Rajan
  • 1,463
  • 12
  • 26