Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

jQuery - get only parent element text without children

I have a web page I'm scraping, and the text I'm looking for is inside a span that contains another span

<div class="someParentDiv">
  <span>this is the text I want   
    <span class="childSpanClass">I don't want this text</span>
  </span>
</div>

I'm trying to get the text I want with a jQuery selection, but when I get the elemnt's text with text(), I will get also the child span's text, which I don't want.

I managed to get only the text I want with

$('div.someParentDiv span').remove('.childSpanClass')

but it seems a little backwards to me (see example), and I'm wondering if there's a better, nicer way to do it. Any ideas?

Upvotes: 1

Views: 4588

Answers (3)

KooiInc
KooiInc

Reputation: 122996

Without JQuery: pick the textContent of the first child of the span element in div.someParentDiv. The first child is the TEXT_NODE (see MDN) of that span, which is a (non visible) separate node. With JQuery use $('.someParentDiv span').contents().first('[nodeType=3]').text();

var res = document.querySelector('#result');

// no jquery
res.innerHTML = 'DOM: ' + 
                 document.querySelector('.someParentDiv span').firstChild.textContent;

// jquery

res.innerHTML += '<br>JQuery: ' +  
                 $('.someParentDiv span').contents().first('[nodeType=3]').text();
#result {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someParentDiv">
  <span>this is the text I want   
    <span class="childSpanClass">I don't want this text</span>
  </span>
</div>

<div id="result"></div>

Upvotes: 1

Lg102
Lg102

Reputation: 4908

You could filter away everything that is not plain text by looping all contents:

var node = $('.someParentDiv > span').contents().filter(function() {
    return this.nodeType == 3; // text node
});

alert(node.text());

Upvotes: 3

Related Questions