1

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?

Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59

3 Answers3

3

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());
Lg102
  • 4,733
  • 3
  • 38
  • 61
1

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>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

Similar problem:

jQuery get .text() but not the text in span

NodeType explained

http://code.stephenmorley.org/javascript/dom-nodetype-constants/

Community
  • 1
  • 1
Zongor Lajos
  • 37
  • 1
  • 3