1

I currently have the following

<div class ="parent">
  <div class="inner">Hello
    <div>Goodbye</div>
  </div>
</div>

<div class ="parent">
  <div class="inner">Hello
    <div>Goodbye</div>
  </div>
</div>

I am currently using $(div.parent).each(function(index,item) to iterate through each parent which works perfectly.

My problem is that I need to select the word hello. I am currently using $(item).text() but it is always returning HelloGoodBye which is a problem. I need to ignore any other div.

Any help appreciated thanks.

James Mclaren
  • 666
  • 4
  • 10
  • 25
  • See this post, maybe it will help: http://stackoverflow.com/questions/3268556/select-only-text-of-an-element-not-the-text-of-its-children-descendants – udidu Aug 08 '12 at 15:24

4 Answers4

1

Instead of using the jQuery.text() method, I'm going to recommend finding the first childNode which will be that textnode you're looking for:

​var divs = document.getElementsByClassName('inner'),
    i = 0;
for (i = divs.length; i--;) {
  console.log(divs[i].childNodes[0]);   
}

OR

var divs = $('.inner');
divs.each(function() {
  console.log(this.childNodes[0]);
});

Keep in mind that the childNodes method will not be recognized by jQuery.

Nick Beranek
  • 2,721
  • 1
  • 19
  • 14
  • Good answer Nick. And as an addition [here is the fiddle](http://jsfiddle.net/lalatino/966Wx/). – Stano Aug 18 '12 at 19:48
0

Try

$('div.parent').not('.parent .inner div').each(function(index,item)

Alternately

$(div.parent:not('.inner div').each(function(index,item)

http://api.jquery.com/not/

JGrubb
  • 869
  • 5
  • 14
  • This didn't seem to work for me. However it may due to the DiV's being replaced at some point. For example, the Div called 'inner' may be replaced with a div that does not have a class name – James Mclaren Aug 08 '12 at 15:26
  • This isn't going to work. `$(item).text();` will still pull the text from the final div. – White Elephant Aug 08 '12 at 15:27
0

The subject has been discussed before here with bunch of suitable solutions: Using .text() to retrieve only text not nested in child tags

Community
  • 1
  • 1
0

You could achieve this by cloning each element, removing the unwanted div and then grabbing the text.

$('div.parent div.inner').each(function(index,item) {
    $this = $(item).clone();
    $this = $this.find('div').remove();
    $this.text();
});​

Here is a JS Fiddle with the code and HTML above in action: http://jsfiddle.net/L8T7s/

White Elephant
  • 1,361
  • 2
  • 13
  • 28