Jquery: select a child div at its index inside a parent div
If I have:
<div id='parent'>
<table>
<tr>
<td>
<div id='child1'></div>
</td>
</tr>
<tr>
<td>
<div id='child2'></div>
</td>
</tr>
</table>
</div>
I tried: $('#parent> table > tr:eq(1) > div');
I would like to select a certain child div at its index. For example, I would like to select the second child div child2. A trivial solution is:
var div2 = $('#child2');
But I would rather like to do so with the parent div:
var div2 = $('#parent div')...get(1); // 1 is the index.
W开发者_Python百科ould this be possible?
You can do it using the :eq()
selector like this:
$("#parent > div:eq(1)")
Or if it's dynamic and you need to pass it in, use .eq()
like this:
$("#parent > div").eq(1)
In both of these we're using 1
because it's a 0-based index, so 1
is the 2nd child.
You will want the children()
function
E.g:
$('#parent').children()[1];
Use the :nth-child() selector.
E.g.
$('#parent div:nth-child(2)');
Update due to comment
$('#parent > div:nth-child(2)');
There are couple of simple ways to do this:
var div2 = $("#parent > div:eq(1)")
When using the "eq" selector, note that it is zero-based, so this will, in fact, select the 2nd div within the #parent div.
A second way is:
var div2 = $("#parent > div:nth-child(2)")
The "nth-child" selector is not zero based, so "nth-child(2)" will also select the 2nd div. You can also select odd and even divs via "nth-child(even)" and "nth-child(odd)". It will even evaluate equations in the parenthesis - you can read more about it in the jQuery documentation here.
精彩评论