$(t).html()
returns
test1 test2
I want to retrieve the second td<
Use .find()
method
$(t).find("td:eq(1)");
td:eq(x) // x is index of child you want to retrieve. eq(1) means equal to 1.
//1 denote second element
It's surprising to see that nobody mentioned the native JS way to do this..
Just access the children property of the parent element. It will return a live HTMLCollection of children elements which can be accessed by an index. If you want to get the second child:
parentElement.children[1];
In your case, something like this could work: (example)
var secondChild = document.querySelector('.parent').children[1];
console.log(secondChild); // <td>element two</td>
<table>
<tr class="parent">
<td>element one</td>
<td>element two</td>
</tr>
</table>
You can also use a combination of CSS3 selectors / querySelector() and utilize :nth-of-type(). This method may work better in some cases, because you can also specifiy the element type, in this case td:nth-of-type(2)
(example)
var secondChild = document.querySelector('.parent > td:nth-of-type(2)');
console.log(secondChild); // <td>element two</td>
How's this:
$(t).first().next()
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:
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. :)
You can use two methods in jQuery as given below-
Using jQuery :nth-child Selector You have put the position of an element as its argument which is 2 as you want to select the second li element.
$( "ul li:nth-child(2)" ).click(function(){
//do something
});
Using jQuery :eq() Selector
If you want to get the exact element, you have to specify the index value of the item. A list element starts with an index 0. To select the 2nd element of li, you have to use 2 as the argument.
$( "ul li:eq(1)" ).click(function(){
//do something
});
See Example: Get Second Child Element of List in jQuery
I didn't see it mentioned here, but you can also use CSS spec selectors. See the docs
$('#parentContainer td:nth-child(2)')
In addition to using jQuery methods, you can use the native cells
collection that the <tr>
gives you.
$(t)[0].cells[1].innerHTML
Assuming t
is a DOM element, you could bypass the jQuery object creation.
t.cells[1].innerHTML