Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 783
George Avatar asked Mar 21 '13 16:03

George


People also ask

How do you comment out in jQuery?

jQuery comments are started with a double forward slash which tells the interpreter that the following text on the line is not to be processed as JavaScript. jQuery comments can be either inside a function or outside it makes no difference.

How do you uncomment an element in HTML?

Select html code => Use Ctrl+K to comment or uncomment.

How do I uncomment JavaScript code?

Uncomment the code and make sure that the onsubmit event handler works. To do this, assign a new value to message. textContent inside the curly braces of the handler. When you complete that step, try to submit the form by clicking on the “Subscribe” button.

How do you comment out multiple lines in JavaScript?

Multiline (Block) Comments Javascript multiline comments, also known as block comments, start with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/). They do not require a comment delimiter character on every line and may contain newlines.


2 Answers

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);
    }
});
like image 98
smnh Avatar answered Nov 03 '22 02:11

smnh


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/

like image 30
Dom Avatar answered Nov 03 '22 02:11

Dom