Get second child using jQuery
$(t).html()
returns
<td>test1</td><td>test2</td>
I want to retrieve the second td
from the $(t)
object. I searched for a solution but nothing worked for me. Any idea how to get the second element?
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.
I didn't see it mentioned here, but you can also use CSS spec selectors. See the docs
$('#parentContainer td:nth-child(2)')