How do you select in-line text with 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>

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.

Upvotes: 3

Views: 216

Answers (3)

kockburn
kockburn

Reputation: 17616

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

Upvotes: 5

guest271314
guest271314

Reputation: 1

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>

Upvotes: 0

Vladu Ionut
Vladu Ionut

Reputation: 8193

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

or without jquery

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

Upvotes: 2

Related Questions