JQuery: select child div in your index inside 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 specific child div in my index. For example, I would like to select the second child div of child2. Trivial solution:

var div2 = $('#child2');

But I would prefer to do this with the parent div:

var div2 = $('#parent div')...get(1); // 1 is the index.

Is it possible?

+3
source share
4 answers

You can do this using a :eq()selector like this :

$("#parent > div:eq(1)")

Or if it is dynamic and you need to pass it, use .eq()for example this :

$("#parent > div").eq(1)

1, , 0, 1 .

+5

children()

:

$( '# ') () [1];.

0

: nth-child().

.

$('#parent div:nth-child(2)');

-

$('#parent > div:nth-child(2)');
0

:

var div2 = $("#parent > div:eq(1)")

"eq" , , div div #parent.

:

var div2 = $("#parent > div:nth-child(2)")

The nth-child selector is not based on a null value, so nth-child (2) will also select the second div. You can also select the odd and even divs with nth-child (even) and nth-child (odd). He will even appreciate the equations in parentheses - you can read about this in the jQuery documentation here .

0
source

Source: https://habr.com/ru/post/1761530/


All Articles