我正在寻找一种使用 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);
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)