We use jQuery to parse some HTML. I then need to traverse that document and find some elements. Among the elements I need to find, there are the el
From the documentation of the feature you're using for $(string)
(which is the function jQuery( html, [ownerDocument] )
):
When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, we use the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as
<html>
,<title>
, or<head>
elements. As a result, the elements inserted may not be representative of the original string passed.
Try not to use jQuery to manipulate entire HTML documents.
Note, in particular, that a link
node in a standalone snippet of HTML can be "found" just fine.
Well, based on what I can find in the source code of jQuery, the engine itself will not create tags (or fragments) that are not "properly seated". Even when passing a string, jQuery recognizes that the header has already been supplied and will not generate it.
After all, when jQuery is passed a string of HTML, it's actually calling document.createElement
and creating an array list of those elements.
EDIT: After a little more investigation, it looks like it's the browser actually limiting element creation, not jQuery. Either way, you're left with absent tags. Which brings me to my same conclusion below.
As much as I don't like it, may be time for regex/string manipulation.
jQuery can't do it, but your browser can: (Do not try to parse HTML with a regex as someome suggested.)
txt = '<DIV><LINK>a</LINK><B>jelo</B></DIV>';
if(window.DOMParser) {
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
} else { // Internet Explorer
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(txt);
}
xmlDoc.getElementsByTagName('LINK');
Be aware that XML is case sensitive, so you need to search for 'LINK' using the same case as it is in the HTML.
Like @pimvdb pointed, this don't work:
alert($("<div><link>Test</link></div>").find("link").text());
The explanation is right:
Sizzle uses context.getElementsByTagName, which fails because the elements are not in the DOM.
But this way work:
alert(("link", $("<div><link>Test</link></div>")).text());
And for some guys that said the second isn't working: http://jsfiddle.net/ErickPetru/5Qs3M/. But of course it obviously don't find elements that aren't on the DOM (i.e. on the head
).