Frage

So I'm trying to run an each loop in jQuery that has an if statement to determine if the element it's on is the first-child of it's parent and also have the else statement following (this seems to be the difficult part) to have other code run for those.

Everything I've tried and found only seems to work without the if and else..

Any thoughts?

War es hilfreich?

Lösung

Given the following example:

<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

there are a couple of ways to do it

$("table tr td:first-child").each(function() {
    //perform actions on all of the first TD elements
});
$("table tr td:not(:first-child)").each(function() {
    //perform actions on all of the other TD elements
});

Or

$("table tr td").each(function() {
    var td = $(this);
    if (td.is(":first-child")) {
        //perform actions on all of the first TD elements
    }
    else {
        //perform actions on all of the other TD elements
    }
});

Andere Tipps

It can't be that difficult ?

$('.elements').each(function(index, elem) {
     if ( $(elem).is(':first-child') ) {
         // it's a baby
     }else{
         // it's something else
     }
});

FIDDLE

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top