您如何 select 使用 Jquery 嵌入文本?
How do you select in-line text with Jquery?
如何select下方无序列表前面的文字?
<li class="foo">
How can I remove this text?
<ul class="bar">
<li><a href="#">Link</a></li>
</ul>
</li>
我试过这样做:
$('ul.bar').previousSibling().remove();
但我认为这只适用于另一个元素,而且我不完全确定如何处理未包含在标签内的文本。select
是您正在寻找的解决方案。
$('.foo').contents().filter(function(){
return (this.nodeType == 3);
}).remove();
The nodeType property returns the node type, as a number, of the
specified node.
If the node is a text node, the nodeType property will return 3.
非jQuery版本:
获取父节点。获取父节点的所有子节点。将节点集合转换为数组。遍历数组。在每次迭代时检查 nodeType。如果 nodeType === 3
那么它是一个文本节点。然后删除。
Array.prototype.slice.call(document.getElementById('parent_node_id_here').childNodes, 0).forEach(function (value) {
if (value.nodeType === 3) {
value.remove();
}
});
$(".foo").contents().get(0).remove()
或没有jquery
document.getElementsByClassName("foo")[0].childNodes[0].remove()
尝试
$(".foo").replaceWith($.parseHTML($(".foo").html()).slice(1));
$(".foo").replaceWith($.parseHTML($(".foo").html()).slice(1));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="foo">
How can I remove this text?
<ul class="bar">
<li><a href="#">Link</a></li>
</ul>
</li>
如何select下方无序列表前面的文字?
<li class="foo">
How can I remove this text?
<ul class="bar">
<li><a href="#">Link</a></li>
</ul>
</li>
我试过这样做:
$('ul.bar').previousSibling().remove();
但我认为这只适用于另一个元素,而且我不完全确定如何处理未包含在标签内的文本。select
是您正在寻找的解决方案。
$('.foo').contents().filter(function(){
return (this.nodeType == 3);
}).remove();
The nodeType property returns the node type, as a number, of the specified node. If the node is a text node, the nodeType property will return 3.
非jQuery版本:
获取父节点。获取父节点的所有子节点。将节点集合转换为数组。遍历数组。在每次迭代时检查 nodeType。如果 nodeType === 3
那么它是一个文本节点。然后删除。
Array.prototype.slice.call(document.getElementById('parent_node_id_here').childNodes, 0).forEach(function (value) {
if (value.nodeType === 3) {
value.remove();
}
});
$(".foo").contents().get(0).remove()
或没有jquery
document.getElementsByClassName("foo")[0].childNodes[0].remove()
尝试
$(".foo").replaceWith($.parseHTML($(".foo").html()).slice(1));
$(".foo").replaceWith($.parseHTML($(".foo").html()).slice(1));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="foo">
How can I remove this text?
<ul class="bar">
<li><a href="#">Link</a></li>
</ul>
</li>