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

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?


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

You can comment the element out by doing the following:

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

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


I'm impresed nobody gave the following solution. The following solution require a container. This container will have inside, the 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/