5

Some background:
I'm developing a web based mobile application using JavaScript. HTML rendering is Safari based. Cross domain policy is disabled, so I can make calls to other domains using XmlHttpRequests. The idea is to parse external HTML and get text content of specific element.
In the past I was parsing the text line by line, finding the line I need. Then get the content of the tag which is a substring of that line. This is very troublesome and requires a lot of maintenance each time the target html changes.
So now I want to parse the html text into DOM and run css or xpath queries on it.
It works well:

$('<div></div>').append(htmlBody).find('#theElementToFind').text()

The only problem is that when I use the browser to load html text into DOM element, it will try to load all external resources (images, js files, etc.). Although it isn't causing any serious problem, I would like to avoid that.

Now the question:
How can I parse html text to DOM without the browser loading external resources, or run js scripts ?
Some ideas I've been thinking about:

  • creating new document object using createDocument call (document.implementation.createDocument()), but I'm not sure it will skip the loading of external resources.
  • use third party DOM parser in JS - the only one I've tried was very bad with handling errors
  • use iframe to create new document, so that external resources with relative path will not throw an error in console
m_vitaly
  • 11,856
  • 5
  • 47
  • 63

2 Answers2

5

It seems that the following piece of code works great:

var doc = document.implementation.createHTMLDocument("");
doc.documentElement.innerHTML = htmlBody;
var text = $(doc).find('#theElementToFind').text();

external resources aren't loaded, scripts aren't being evaluated.

Found it here: https://stackoverflow.com/a/9251106/95624

Origin: https://developer.mozilla.org/en/DOMParser#DOMParser_HTML_extension_for_other_browsers

Community
  • 1
  • 1
m_vitaly
  • 11,856
  • 5
  • 47
  • 63
  • Great, +1 and favourited. Is it guaranteed that there is no external loading/script evaluation or is it rather "it just works" at the moment? If this can change any time in the future it may not be a very robust solution. – pimvdb Aug 15 '12 at 12:06
  • This is great, but is has one issue, it does not copy the attributes on the HTML node, but this is minor as it achieves the major part of the issues listed above. – joseeight Feb 20 '13 at 07:47
1

You can construct jQuery object of any html string, without appending it to the DOM:

$(htmlBody).find('#theElementToFind').text();
Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89