How do you select in-line text with Jquery?

2019-05-11 00:35发布

问题:

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>