Tuesday, April 5, 2011

getting a specific adjacent element in jquery

hello,

if I have the following table:

<tr class="alternate">
    <td>{$order.titel}</td>
    <td>{$order.auteur}</td>
    <td>&euro;{$order.prijs}</td>
    <td>{$order.aantal}</td>
    <td>&euro; {$order.aantal*$order.prijs}</td>
<tr>

and inside jquery I currently have the 4th td selected, how can i get the data from within the first td, keeping in mind that I start looking from the 4th td (eg. the 4th td is 'this')?

From stackoverflow
  • You can use the prev() method which returns the preceding sibling.

    var first = $(this).prev().prev().prev();
    
  • You can call the prevUntil() method to match the first <td> element:

    var first = $(this).prevUntil("td:eq(0)");
    
  • var first = $(this).siblings().first();
    

    Or, for one of the other elements:

    var second = $(this).siblings().eq(1);
    
    Frédéric Hamidi : Shouldn't that be `:eq(0)`?
    Harmen : @Frédéric Hamidi: No, eq is 1-based
    Frédéric Hamidi : @Harmen, [really](http://api.jquery.com/eq-selector/)? Documentation says it's zero-based.
    lonesomeday : Yes, it's zero-based. Hence `second = ` :-)
    Harmen : @Frédéric Hamidi: You're right, I'm confused with `nth-child()` which is 1-based
    Frédéric Hamidi : @lonesomeday, you're right, I was blinded by the question mentioning the first `` :)

0 comments:

Post a Comment