How do I get an HTML comment with javascript
You have to travers the DOM to get it.
The nodeType
of the comment DOM element is 8
if( oNode.nodeType === 8 ) {
oNode.parentNode.removeChild( oNode );
}
would be an approach
Using a NodeIterator (IE >= 9)
The best method is to use a dedicated NodeIterator instance iterating all comments contained in a given root element.
See it in action!
function filterNone() {
return NodeFilter.FILTER_ACCEPT;
}
function getAllComments(rootElem) {
var comments = [];
// Fourth argument, which is actually obsolete according to the DOM4 standard, is required in IE 11
var iterator = document.createNodeIterator(rootElem, NodeFilter.SHOW_COMMENT, filterNone, false);
var curNode;
while (curNode = iterator.nextNode()) {
comments.push(curNode.nodeValue);
}
return comments;
}
window.addEventListener("load", function() {
console.log(getAllComments(document.body));
});
Using a custom-made DOM traversal (to support IE < 9 as well)
If you have to support older browsers (e.g. IE <9), you need to traverse the DOM yourself and extract those elements whose node type is Node.COMMENT_NODE
.
See it in action!
// Thanks to Yoshi for the hint!
// Polyfill for IE < 9
if (!Node) {
var Node = {};
}
if (!Node.COMMENT_NODE) {
// numeric value according to the DOM spec
Node.COMMENT_NODE = 8;
}
function getComments(elem) {
var children = elem.childNodes;
var comments = [];
for (var i=0, len=children.length; i<len; i++) {
if (children[i].nodeType == Node.COMMENT_NODE) {
comments.push(children[i]);
}
}
return comments;
}
Extracting a node's contents and delete it
Independent of the way you choose from above, you receive the same node DOM objects.
Accessing a comment's contents is as easy as commentObject.nodeValue
.
Deleting a comment is a bit more verbose: commentObject.parentNode.removeChild(commentObject)
Here is a JQuery plugin that retrieves the comments:
http://www.bennadel.com/blog/1563-jQuery-Comments-Plug-in-To-Access-HTML-Comments-For-DOM-Templating.htm
The basic idea is to look at nodes
, not elements
:
http://www.w3schools.com/htmldom/dom_nodes.asp
You start with document
object, and iterate through them using childNodes
collection. You have to check for node.nodeType == 8
which will return just the comment nodes (note that you need to iterate through child nodes recursively).