Joseph Davoli
Joseph Davoli

Reputation: 3

jQuery selector last element of of next sibling

I recently had to write code to search a page for the value of a field associated with a title. The HTML structure is in the following form:

    <table><tr>
    ...etc...
    <td><div><span>Type of Fruit:</span></div></td>
    <td><span><div><span><div>Orange</div></span></div></span></td>
    ...etc...
    </tr></table>

I solved the problem with the following jQuery:

    var strFruitType = $('span').filter(function(){ 
          return $(this).text() === 'Type of Fruit:';
    }).closest('td').next().find(':last').text().trim();

    //Evaluate Fruit Type.
    switch(strFruitType) {
    ...etc...

Is this the most straightforward or efficient way to locate the last element of the next sibling of something?

Upvotes: 0

Views: 78

Answers (1)

Frank Modica
Frank Modica

Reputation: 10516

If you have no control of the HTML, what you have looks pretty good. Just a couple of things:

If searching for a string that contains "Type of Fruit:" is OK, you could do:

$('span:contains("Type of Fruit:")').closest('td').next().find(':last').text().trim();

Which you may even be able to shorten to:

$('td:contains("Type of Fruit:")').next().find(':last').text().trim();

Also, I'm not sure how simplified your example is, but it looks like you may be using :last to find the deepest element in the sibling td element. But :last really finds the last direct child. So if your td could have more than one direct child like this:

<td>
    <span><div><span><div>Orange</div></span></div></span>
    <span><div><span><div>Apple</div></span></div></span>
</td>

You'd end up with "Apple", but it's because :last found the second span directly inside the td. So if your td will only ever have one direct child, then you don't need :last.

This leaves us with:

$('td:contains("Type of Fruit:")').next().text().trim();

Upvotes: 3

Related Questions