I am trying to setup a nested table function. So within the function I am passing a selected element and I want to select only the children/direct-descendants td/tr of that table and NOT the nested table’s td/tr elements. Here is a little example that I setup.
<table class="top">
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>
<table class="nested">
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>4</td>
</tr>
</table>
</td>
</tr>
</table>
<div id="results"></div>
and the jQuery / Javascript to go with it…
var tbl = $(".top");
var r = $("div#results");
$(r).html("");
$(r).append("var tbl = $(\".top\")</br>")
$(r).append("$(tbl).find(\"td\").length:" + $(tbl).find("td").length.toString() + "</br>");
$(r).append("$(\"td\", tbl).length: " + $("td", tbl).length.toString() + "</br>");
$(r).append("$(tbl).children(\"tbody\").children(\"tr\").children(\"td\").length: " + $(tbl).children("tbody").children("tr").children("td").length.toString() + "</br>");
The results are as follows…
var tbl = $(“.top”) (to simulate the passed selector)
$(tbl).find(“td”).length:12 (selects ALL td elements)
$(“td”, tbl).length: 12 (selects ALL td elements, same as above)
$(tbl).children(“tbody”).children(“tr”).children(“td”).length: 6 (selects the proper elements, but the jQuery chain seems too long and strict for what I want to do)
Any help to find the proper selector for the children elements of the top level table is much appreciated! Thanks!
Update: here is the jsFiddle.
Working fiddle using direct descendant (
>) selector: http://jsfiddle.net/3T9sN/Of course, you can reuse some of the contexts here to make the query more efficient, such as:
Fiddle: http://jsfiddle.net/3T9sN/1/