JQuery comment / uncomment <! - element ->
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
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) == '<!--'; } +2
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