Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get second child using jQuery

People also ask

How do you target a second child in Javascript?

you just need to load it into your website, then you can target the element in your exemple using: $('. parent div:nth-child(2)') It's that easy.

Which of the following CSS selectors will select the second div in jQuery?

myclass:eq(1)" ) selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification. Prior to jQuery 1.8, the :eq(index) selector did not accept a negative value for index (though the . eq(index) method did).

What is the use of EQ in jQuery?

The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 (not 1).


grab the second child:

$(t).children().eq(1);

or, grab the second child <td>:

$(t).children('td').eq(1);

See documentation for children and eq.


Here's a solution that maybe is clearer to read in code:

To get the 2nd child of an unordered list:

   $('ul:first-child').next()

And a more elaborated example: This code gets the text of the 'title' attribute of the 2nd child element of the UL identified as 'my_list':

   $('ul#my_list:first-child').next().attr("title")

In this second example, you can get rid of the 'ul' at the start of the selector, as it's redundant, because an ID should be unique to a single page. It's there just to add clarity to the example.

Note on Performance and Memory, these two examples are good performants, because they don't make jquery save a list of ul elements that had to be filtered afterwards.


How's this:

$(t).first().next()

MAJOR UPDATE:

Apart from how beautiful the answer looks, you must also give a thought to the performance of the code. Therefore, it is also relavant to know what exactly is in the $(t) variable. Is it an array of <TD> or is it a <TR> node with several <TD>s inside it? To further illustrate the point, see the jsPerf scores on a <ul> list with 50 <li> children:

http://jsperf.com/second-child-selector

The $(t).first().next() method is the fastest here, by far.

But, on the other hand, if you take the <tr> node and find the <td> children and and run the same test, the results won't be the same.

Hope it helps. :)


I didn't see it mentioned here, but you can also use CSS spec selectors. See the docs

$('#parentContainer td:nth-child(2)')

Try this:

$("td:eq(1)", $(t))

or

$("td", $(t)).eq(1)