9

次のような要素をjQueryでコメントにラップする方法を探しています。

<!--
<div class="my_element"></div>
-->

また、コメントを削除する方法。

これは可能ですか?

4

4 に答える 4

20

要素をコメントでラップするには、またはより具体的には、要素をその要素の 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);
    }
});
于 2013-03-21T19:03:03.067 に答える
3

次のようにして、要素をコメントアウトできます。

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

デモ:http: //jsfiddle.net/dirtyd77/THBpD/27/

于 2013-03-21T18:02:40.000 に答える
-2

ラッピング用?

function wrap(jQueryElement){
    jQueryElement.before("<!--").after("-->");
}

ただし、一度ラップされたコメントを見つけることがどれほど成功するかはわかりません。正規表現を使用したbody要素のテキスト検索はオプションです。

またはこれ-jqueryを使用してdomからhtmlコメントを削除することは可能ですか?

于 2013-03-21T16:58:53.627 に答える