javascript - jQuery each: If element is first-child else - Stack Overflow

So I'm trying to run an each loop in jQuery that has an if statement to determine if the element i

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?

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?

Share Improve this question asked Apr 4, 2014 at 18:07 ReubenReuben 2,7516 gold badges32 silver badges47 bronze badges 2
  • 1 Could you post some code of what you are doing – jwatts1980 Commented Apr 4, 2014 at 18:09
  • "Any thoughts?" About what??? – A. Wolff Commented Apr 4, 2014 at 18:10
Add a ment  | 

2 Answers 2

Reset to default 5

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
    }
});

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742382402a4433381.html

相关推荐

  • javascript - jQuery each: If element is first-child else - Stack Overflow

    So I'm trying to run an each loop in jQuery that has an if statement to determine if the element i

    2天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信