How do you select in-line text with Jquery?

巧了我就是萌 提交于 2019-12-22 10:33:46

问题


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>

I tried doing something like this:

$('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.


回答1:


Is the solution you're looking for.

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

Demo here

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.


Non jQuery version:

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();
    }
});



回答2:


$(".foo").contents().get(0).remove()

or without jquery

document.getElementsByClassName("foo")[0].childNodes[0].remove()



回答3:


Try

$(".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>


来源:https://stackoverflow.com/questions/28776119/how-do-you-select-in-line-text-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!