rdodev rdodev - 3 months ago 29
AngularJS Question

AngularJS $http HTML Parser

All, we're developing a webapp with AngularJS and we have a use case/requirement (that won't happen very often at all) where we will need to retrieve a complete HTML document from our static server. However, it appears that the $http object returns a raw HTML string as its 'data'. We are trying to avoid using an external library (like jQuery, for instance), but we need to parse that raw HTML string into a queriable DOM object. We could use an iframe and be done with it, but we're also trying to avoid using iframes for well-known reasons.

So, the question is: does AngularJS have a parser for HTML (as it does for JSON)? Or else, what's the most graceful way to handle this case?

P.S.: We tried sifting through Angular's API docs, but in all honesty they are hit-or-miss and unintuitive to navigate around.

Answer

If you need to get a DOM element from the string programmatically, parsing html into a DOM object is pretty simple.

Basically you'd use DOMParser.

var parser = new DOMParser();
var doc = parser.parseFromString('<div>some html</div>', 'text/html');
doc.firstChild; //this is what you're after.

From there if you wanted to query to get elements from it with vanilla JS (meaning, you don't want to use JQuery for some reason), you can do this:

//get all anchor tags with class "test" under a div.
var testAnchors = doc.firstChild.querySelectorAll('div a.test'); 

... but note: querySelectorAll is only supported in IE8 and higher.

EDIT: additional approach...

The "wrap" method:

var div = document.createElement('div');
div.innerHTML = '<div>some html</div>';
var result = div.childNodes;

... do note that this method will return HTMLUnknownElements if you put SVG or MathML into it. They'll "look" normal, but they won't work.

Comments