开发者

jquery get first level td elements within an existing selection

Like some existing examples I want to select only the first level of TD's within a selector, the difference here is that the operation is on an existing selection.

Let's say I have a table like so...

<table border=1>
<tr trid="1">
   <td>cell 1</td>
   <td>cell 2</td>
   <td>cell 3</td>
</tr>
<tr trid="2">
   <td>cell 1</td>
   <td>

       <table border=1>
        <tr>
           <td>cell 1</td>
           <td>cell 2</td>
           <td>cell 3</td>
        </tr>
        <tr>
           <td>cell 1</td>
           <td>cell 2</td>开发者_JS百科
           <td>cell 3</td>
        </tr>
       </table>

   </td>
   <td>cell 3</td>
</tr>
<tr trid="3">
   <td>cell 1</td>
   <td>cell 2</td>
   <td>cell 3</td>
</tr>
</table>

I want to initially traverse this particular table row by row. I only want to traverse the rows that have a custom attribute of "trid".

I managed to get this far...

    $('tr[trid]').each(function(index)
    {
        //gets properties of TR here

        $('td',this).each(function(index)
        {
            $(this).css('background-color', 'red'); //turn my cells red
        });

    });

Now this works but I only want the first level of Cells. So I want the TD loop to ignore the second level of td's.

I know if the outer loop used tr[trid]>td this would work however I then skip an important part of the loop. Is there syntax I can use to operate like this on the existing selection, i.e. ensuring the parent of the selected td has the tr[tabid].

This is quite particular in that I cannot add new styles or change the existing HTML in anyway. Also the order of the JQuery loop is also important since it outputs as it runs and needs to retain it's sequence.

Thanks :)


Instead of

$('td',this).each(function(index)

use

$(this).children('td').each(function(index)

example: http://jsfiddle.net/gaby/tz2jt/1/


or the more cryptic (but you get the idea)

$('> td',this).each(function(index)

example: http://jsfiddle.net/gaby/tz2jt/


You can use the .children() method which traverses the immediate children of the elements you're calling it on.

$(this).children('td').each(function() {
    $(this).css('background-color', 'red');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜