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?

3
  • May be regex helps? Commented Jan 27, 2021 at 19:56
  • Thanks for the suggestion @rootkonda I was hoping for a cleaner approach, but that will be my last resort Commented Jan 27, 2021 at 19:56
  • 1
    Have you seen this already ? - stackoverflow.com/questions/3103962/… Commented Jan 27, 2021 at 19:59

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.