Insert HTML block after a specific HTML comment

2019-08-04 12:27发布

问题:

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

回答1:

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