Jonathan Eckman
Jonathan Eckman

Reputation: 2077

Select element inside next element

I need to select each $('div span:eq(0)').text() inside $('div#first'). How can I string these two selectors together?

<div id="first">Some stuff to be ignored.</div>
<div>
  <div>
    <ul>
      <li>
        <span>Some text</span> <!-- need this -->
        <span>Skipped text</span>
      </li>
    </ul>
  </div>
  <div>
    <ul>
      <li>
        <span>Some text</span>  <!-- and this -->
        <span>Skipped text</span>
      </li>
    </ul>
  </div>
  <!-- this pattern continues unknown # of times -->
</div>

Upvotes: 0

Views: 66

Answers (2)

Sly
Sly

Reputation: 1165

$('div span:eq(0)', 'div#first').text()

Or if you want to handle them one at a time:

$('div span:eq(0)', 'div#first').each(function() {
  console.log($(this).text());
});

If you're talking about putting those spans in 'div#first', you can use:

$('div#first').append($('div span:eq(0)'));

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79840

Try using li instead of div.

// Using #first.next()-v as #first just has a &nbsp;
$('li', $('#first').next()).find('span:eq(0)').text('Updated text');

DEMO: http://jsfiddle.net/rFUB8/1/

Upvotes: 2

Related Questions