The second child of a second child - Jquery
I wanna know how can I get a value of a child of a child. I have this...
<table id="table4">
<tr>
<td>Id:</td>
<td>Name:</td>
</tr>
<tr>
<td>1515</td>
<td>Thiago</td>
</tr>
</table>
In Jquery, I wanna do something like this...
var id = $("#table4:nth-child(2) tr:nth-child(1)").val();
How can I do this work? The first <td>
of the second <tr>
. I know that I can use "class" and "id" to make it easier, but in this case I can't do that for others reasons.
PS. Sorry about th开发者_JAVA百科e bad English, I'm a noob in this language.
Thanks.
Like this:
var id = $("#table4 tr:nth-child(2) td:nth-child(1)").text();
You can test it out here. The :nth-child
selector applies to the child, for instance the first is saying "a <tr>
that is a second child of its parent", rather than your attempted version, which would mean "the second child of this <tr>
".
Also, use .text()
to get an elements text, rather than .val()
which is for input type elements.
This isn't a fully jQuery solution, but just thought I'd point out that you could do this:
var txt = $("#table4")[0].rows[1].cells[0].innerHTML;
Or if there will be any HTML markup you want to avoid, you could do this:
var cell = $("#table4")[0].rows[1].cells[0];
var txt = cell.innerText || cell.textContent;
精彩评论