如何使用Jquery选择内联文本? [英] How do you select in-line text with Jquery?

查看:55
本文介绍了如何使用Jquery选择内联文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何选择下面无序列表前面的文字?

How can I select the text infront of the unordered list below?

<li class="foo">
   How can I remove this text?
   <ul class="bar">
       <li><a href="#">Link</a></li>
   </ul>
</li>

我尝试过这样的事情:

$('ul.bar').previousSibling().remove();

但我认为这只适用于其他元素,我不完全确定如何去关于选择不包含在标签内的文本。

But I think that would only work with another element, and I'm not entirely sure how to go about selecting text that isn't contained inside tags.

推荐答案

是您正在寻找的解决方案。

Is the solution you're looking for.

$('.foo').contents().filter(function(){
    return (this.nodeType == 3);
}).remove();

在这里演示


nodeType属性返回
的节点类型(数字)指定的节点。
如果节点是文本节点,则nodeType属性将返回3.

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版本:


Non jQuery version:

获取父节点。获取Parent的所有Children节点。将节点集合转换为数组。循环遍历数组。在每次迭代时检查nodeType。如果 nodeType === 3 那么它就是一个文本节点。然后删除它。

Get the Parent Node. Get all the Children nodes of the Parent. Convert the collection of Nodes to an array. Loop through the array. Check the nodeType on every iteration. If the nodeType === 3 then it's a text node. Then delete it.

Array.prototype.slice.call(document.getElementById('parent_node_id_here').childNodes, 0).forEach(function (value) {
    if (value.nodeType === 3) {
        value.remove();
    }
});

这篇关于如何使用Jquery选择内联文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆