JQuery comment / uncomment <! - element ->

I am looking for a way to wrap, using jQuery, an element in a comment, for example:

<!-- <div class="my_element"></div> --> 

as well as a way to delete comments.

Is it possible?

+8
source share
4 answers

To wrap an element with a comment, or more specifically, replace the element with a node comment that has this HTML element:

 my_element_jq = $('.my_element'); comment = document.createComment(my_element_jq.get(0).outerHTML); my_element_jq.replaceWith(comment); 

To return it back:

 $(comment).replaceWith(comment.nodeValue); 

If you don't have a link to the node comment, you need to go through the DOM tree and check the nodeType each node. If its value is 8, then this is a comment.

For instance:

 <div id="foo"> <div>bar</div> <!-- <div>hello world!</div> --> <div>bar</div> </div> 

JavaScript:

 // .contents() returns the children of each element in the set of matched elements, // including text and comment nodes. $("#foo").contents().each(function(index, node) { if (node.nodeType == 8) { // node is a comment $(node).replaceWith(node.nodeValue); } }); 
+18
source

You can comment on an item by following these steps:

 function comment(element){ element.wrap(function() { return '<!--' + this.outerHTML + '"-->'; }); } 

DEMO: http://jsfiddle.net/dirtyd77/THBpD/27/

+3
source

I am convinced that no one has given the following solution. The following solution requires a container. This container will have inside, commented / uncommented code.

 function comment(element) { element.html('<!--' + element.html() + '-->') } function uncomment(element) { element.html(element.html().substring(4, element.html().length - 3)) } function isCommented(element) { return element.html().substring(0, 4) == '<!--'; } 

Example: https://jsfiddle.net/ConsoleTVs/r6bm5nhz/

+2
source

For packing?

 function wrap(jQueryElement){ jQueryElement.before("<!--").after("-->"); } 

Not sure how successfully you will find comments after they are wrapped. A text search on the body element using regular expressions is an option.

Or this - you can remove the html comment from dom using jquery

-2
source

All Articles