次のような要素をjQueryでコメントにラップする方法を探しています。
<!--
<div class="my_element"></div>
-->
また、コメントを削除する方法。
これは可能ですか?
次のような要素をjQueryでコメントにラップする方法を探しています。
<!--
<div class="my_element"></div>
-->
また、コメントを削除する方法。
これは可能ですか?
要素をコメントでラップするには、またはより具体的には、要素をその要素の HTML を持つコメント ノードに置き換えるには:
my_element_jq = $('.my_element');
comment = document.createComment(my_element_jq.get(0).outerHTML);
my_element_jq.replaceWith(comment);
元に戻すには:
$(comment).replaceWith(comment.nodeValue);
コメント ノードへの参照がない場合は、DOM ツリーを走査してnodeType
各ノードを確認する必要があります。値が 8 の場合、それはコメントです。
例えば:
<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);
}
});
次のようにして、要素をコメントアウトできます。
function comment(element){
element.wrap(function() {
return '<!--' + this.outerHTML + '"-->';
});
}
デモ:http: //jsfiddle.net/dirtyd77/THBpD/27/
ラッピング用?
function wrap(jQueryElement){
jQueryElement.before("<!--").after("-->");
}
ただし、一度ラップされたコメントを見つけることがどれほど成功するかはわかりません。正規表現を使用したbody要素のテキスト検索はオプションです。