I have a document with a debugging comment in it that looks like this:
Is there a way to query the DOM to a
The nodeType
core property allows you to differentiate between types of nodes. In this particular case, 8 represents comments. As they have no selector, you'll need to loop through their parent to get them (which sucks, I know). The following code filters them out for you:
$("*").contents().filter(function(){
return this.nodeType == Node.COMMENT_NODE;
})
And my own jQuery-less version, because some people don't have it:
function getAllComments() {
var t = [],
recurse = function (elem) {
if (elem.nodeType == Node.COMMENT_NODE) {
t.push(elem);
};
if (elem.childNodes && elem.childNodes.length) {
for (var i = 0; i < elem.childNodes.length; i++) {
recurse(elem.childNodes[i]);
};
};
};
recurse(document.getElementsByTagName("html")[0]);
return t;
};
If you'd like to search on a specific node, re-bind the document.getElementsByTagName
call to a variable of your choosing.
Edit: fiddle to demonstrate the use, done by Jason Sperske!
There's the TreeWalker
APIs:
var tw = document.createTreeWalker(document, NodeFilter.SHOW_COMMENT, null, null),
comment;
while (comment = tw.nextNode()) {
// ...
}
This isn't supported by IE8 and lower.
T.J. in the comments provided a link to the specs. I kind of always use just TreeWalkers, but in your case a NodeIterator
is fine too.