jQuery comment/uncomment <!--element-->

comments, element, javascript, jquery

Solution

To wrap an element with comment, or more specifically to replace an element with a comment node having that element's HTML:

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

To switch it back:

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

If you don't have the reference to the comment node then you need to traverse the DOM tree and check `nodeType` of each node. If its value is 8 then it is a comment.

For example:

<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);
    }
});

Problem

I am looking for a way to wrap, with jQuery, an element into a comment, like: ``` <!-- <div class="my_element"></div> --> ``` and also a way to remove the comments. Is this possible?

Original source

Related problems