How do I get an HTML comment with javascript

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)