0

Suppose I download an html doc with Ajax. How do I parse it? Can I construct an html doc object and use DOM methods? If not, what's the solution?

Henrik3
  • 27
  • 4
  • How exactly would you like to parse it? That is, what's your goal? If your just want to add it to the page, you can just add it to an element by setting its `innerHTML` property to the Ajax result. Or do you want to iterate over all elements? – Constantin Groß Oct 26 '17 at 17:13
  • @Connum I want to grab some data in there. No, I don't want to add it to the page as is. That's impossible anyway because it's a complete html doc. – Henrik3 Oct 26 '17 at 17:15
  • @Henrik3, you may want to look at the following answer: [Parse a HTML String with JS](https://stackoverflow.com/questions/10585029/parse-a-html-string-with-js) – dey.shin Oct 26 '17 at 17:17
  • @dey.shin Ah yes, you can create an element without attaching it to the present document. And add the string to it as inner html. But that makes neither valid html nor valid xml. Isn't that a problem? At best it can be regarded as xml, but then the html DOM is absent, yes? – Henrik3 Oct 26 '17 at 17:24

1 Answers1

0

If you don't need to support IE < 9, you can use DOMParser(). Assuming your ajax response is held in a variable called yourAjaxResponse:

domParser = new DOMParser();
parsedDocument = domParser.parseFromString(yourAjaxResponse,"text/html");

Now you can use dom functions like getElementsByTagName(), getElementsByClassName(), getElementsById or querySelector()/querySelectorAll() on parsedDocument to access any nodes.

Update: In case you need to support older browsers, there are JS polyfills out there, for example: https://gist.github.com/eligrey/1129031

Constantin Groß
  • 10,719
  • 4
  • 24
  • 50