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?
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.
Select html code => Use Ctrl+K to comment or uncomment.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With