jQuery注释/取消注释<! - element - >

Geo*_*rge 9 javascript jquery comments element

我正在寻找一种方法,用jQuery将一个元素包装到注释中,如:

<!--
<div class="my_element"></div>
-->
Run Code Online (Sandbox Code Playgroud)

还有一种删除评论的方法.

这可能吗?因为我找不到任何相关的东西.

smn*_*mnh 20

要使用注释包装元素,或者更具体地用具有该元素的HTML的注释节点替换元素:

my_element_jq = $('.my_element');
comment = document.createComment(my_element_jq.get(0).outerHTML);
my_element_jq.replaceWith(comment);
Run Code Online (Sandbox Code Playgroud)

要切换回来:

$(comment).replaceWith(comment.nodeValue);
Run Code Online (Sandbox Code Playgroud)

如果您没有对comment节点的引用,那么您需要遍历DOM树并检查nodeType每个节点.如果它的值是8那么它是一个注释.

例如:

<div id="foo">
    <div>bar</div>
    <!-- <div>hello world!</div> -->
    <div>bar</div>
</div>
Run Code Online (Sandbox Code Playgroud)

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);
    }
});
Run Code Online (Sandbox Code Playgroud)