Skip to content Skip to sidebar Skip to footer

How Do I Get An Html Comment With Javascript

If I have that How do I get this element and change the content with javascript? And if I have a code inside that and I want to delete the tag of com

Solution 1:

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!

functionfilterNone() {
    returnNodeFilter.FILTER_ACCEPT;
}

functiongetAllComments(rootElem) {
    var comments = [];
    // Fourth argument, which is actually obsolete according to the DOM4 standard, is required in IE 11var 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 < 9if (!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)

Solution 2:

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

Solution 3:

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).

Solution 4:

I needed to store a template for an entire web page. But the <template>-tag cannot contain for example an <html>-tag. So I decided to store my template inside an HTML-comment instead.

I put the HTML-comment in a hidden <div> in order to more easily retrieve the text in that specific HTML-comment, and not have to bother with distinguishing it from other HTML-comments.

Here is a demo of how you can retrieve what's inside a HTML-comment by using createTreeWalker.

alert(
  document.createTreeWalker(
    document.getElementById('commentDiv'), 
    NodeFilter.SHOW_COMMENT, 
    null, 
    false
  ).nextNode().nodeValue
);
<p>Getting the text in a HTML-comment.</p><p>I use createTreeWalker to make sure we don't simply capture an empty text node by mistake. You could make the code even simpler, but then you must make sure that the &lt;div>-tag is immediately followed by the "&lt;!--", like this "&lt;div>&lt;!--". But if that breaks because of for example autoformating in an editor, so that you get a line feed in between or so, then the simpler method will fail. That is why I prefere to use the createTreeWalker here.</p><!--
  This is NOT the comment we want to get text from
--><divid="commentDiv"style="display:none;"><!--
    This is THE text, and you can have anything in here
    <>
    <div>
    <script>alert('hello');</script>
    etc.
    except of course an end of HTML-comment.

    An advantage of this way to store a template compared to using
    the <template>-tag, is that the <template>-tag can for example
    not contain a <html>-tag, in case you need to have a template
    for an entire web page.

    Check also my explanation down in the body text for why I use 
    createTreeWalker instead of some simpler code.
  --></div><!--
  This is also NOT the comment we want to get text from
--><p>End of body.</p>

Post a Comment for "How Do I Get An Html Comment With Javascript"