Nathan Nguyễn
Nathan Nguyễn

Reputation: 727

How to get text of element but excluding a child of that element?

I have an HTML snippet:

<li class="as-selection-item">
<a class="as-close">×</a>
Rudy Hamilton
</li>

How can I get the value Rudy Hamilton from li.as-selection-item but without getting the value x from within a.as-close?

Upvotes: 5

Views: 2637

Answers (2)

S&#233;bastien Garmier
S&#233;bastien Garmier

Reputation: 1263

Using jQuery you can use this:

$(".as-selection-item").text();

This will return all the thext inside .as-selection-item and not the html

If you only want the text inside .as-selection-item (not in the anchor) you can use this:

$(".as-selection-item").clone().children().remove().end().text();

This clonese the object, removes the children, and returns the text.

Fiddle

Upvotes: 1

Florian Margaine
Florian Margaine

Reputation: 60717

Solution 1

document.querySelector('.as-close').nextSibling.nodeValue

JSFiddle demo: http://jsfiddle.net/t8Qst/

It uses nextSibling to get the node right after the element with the as-close class.

Solution 2

If you want to get everything inside the li, except the anchor, you can use this:

var li = document.querySelector('.as-selection-item').cloneNode(true);
li.removeChild(li.querySelector('.as-close'));
alert(li.textContent);

You clone the li, remove the anchor from the clone, and just display its text.

JSFiddle demo: http://jsfiddle.net/58pLz/

With jQuery (in case you're already using it), this'd give this:

var li = $('.as-selection-item').clone();
$('.as-close', li).remove();
alert(li.text());

Upvotes: 10

Related Questions