1

I am wondering if I can insert HTML code after a specific HTML comment rather than within an HTML element such as <div>.

For example, I would like to insert the opening tags <div id="OUTER"><div id="INNER"> after the first comment tag below; and the closing tags </div></div> after the second comment tag. Does somebody know how to go about this?

<!-- Insert Opening Tags Below -->


<div id="CONTENT">Page Content Here</div>


<!-- Insert Closing Tags Below-->

Thank you in advance.

Elena

9
  • I don't think that comments are part of the DOM. Commented Sep 2, 2013 at 18:14
  • 1
    Comments can go anywhere. I don't get the question. Commented Sep 2, 2013 at 18:14
  • Just found: stackoverflow.com/questions/1623734/… Commented Sep 2, 2013 at 18:16
  • @OfirBaruch so you are saying that I cannot target the comment tags since they are not part of the DOM, correct? Commented Sep 2, 2013 at 18:20
  • Comments are for developer convenience. You can certainly nest one div inside another without worrying about where the comments go. Most of my documents have no comments at all. Commented Sep 2, 2013 at 18:23

1 Answer 1

2

HTML comment has it's own corresponding Node in DOM hierarchy and it's nodeType property is 8. DOM inspectors like Firebug or Google Console do not show them, however, you can find them by viewing source of the page, if elements are children of the body element, you can filter the childNodes this way:

$('body').contents().each(function(i, elem){
    if (elem.nodeType == 8) {
       // This is a Comment node
       // Comment { data=" Insert Closing Tags Below", length=26, nodeType=8, more...}
       // You can select all the next sibilngs of the first
       // Comment node including the second Comment Node 
       // and then wrap all of them 
    }
});

There is no point in doing what you want, browsers only show the initial version of the document that has been sent by the server and manipulating document using JavaScript doesn't change the source view. furthermore, you can only add Nodes to the document, you can't put some strings in DOM to be parsed as a DOM element, unless you are manipulating innerHTML of another element. I would suggest wrapping the #CONTENT element:

$('#CONTENT').wrap('<div id="OUTER"><div id="INNER"></div></div>');

Which results in:

<!-- Insert Opening Tags Below -->
<div id="OUTER">
   <div id="INNER">
      <div id="CONTENT">Page Content Here</div>
   </div>
</div>
<!-- Insert Closing Tags Below-->
Sign up to request clarification or add additional context in comments.

1 Comment

@@undefined Yes, this is basically what I ended up doing. Thank you so much for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.