19

For example I have a <div class="first"> containig other <div> 's and selected first one and pushed him into variable

variable = $('div.first')

And now I want something like this

$(variable + " > div")

I know, it seems stupid but what if I had an array containig table rows and I need to access columns inside a specific row:

var tableRows = $('table > tbody > tr');
var tableBodyCols = $(tableRows[i]+'> td'); // Doesn't work :(

4 Answers 4

29

Use .children()

var tableBodyCols = tableRows.children('td');

Or a context selector:

var tableBodyCols = $('> td', tableRows);

Both are equivalent but the former is easier to read imho.

Here's a fiddle demonstrating both.


And to iterate over all sets of children of each table row:

tableRows.each(function() {
    var tableBodyCols = $(this).children('td');
    //...
});

But if you really prefer a for loop or you need to get a specific row's columns, then eq is your friend.

for (var i = 0; i < tableRows.length; i++) {
    var tableBodyCols = tableRows.eq(i).children('td');
    //...
}

Here's the updated fiddle.

5
  • the former is much more efficient too
    – Alnitak
    Apr 2, 2013 at 12:30
  • @Alnitak Yes nicely noted, it doesn't create a new jQuery object from scratch too. =] Apr 2, 2013 at 12:33
  • My english is bad, and I was thinking that children() selector selects only first child (I thought "children" is a singular form of "childrens"). Anyway, thank you very much. Context selector looks very nice. Apr 2, 2013 at 12:45
  • @tumoxep heheh no problem, child (as in :first-child, :last-child) is the singular form, children is the plural. :P Apr 2, 2013 at 12:46
  • children function selects all descendants, not only first level children as > (jsfiddle). This works in the example because you don't have nested td.
    – nessa.gp
    Jun 14, 2017 at 9:42
3

You can't do $(variable + " > div") because variable is not a string but a jquery element.

But you can try:

variable.children("div");
0

To get the cells of the row of index i, you may use

  var tableBodyCols = $('td', tableRows[i]);

If you really may have more than one level of td, use

  var tableBodyCols = tableRows.eq(i).children('td');

or use the native dom object :

  var tableBodyCols = tableRows[i].cells;
1
  • that first is not strictly a parent > child search but a .find(). The third is also now just an array, not a jQuery collection... ;-)
    – Alnitak
    Apr 2, 2013 at 12:29
0

If you want all <td> cells, use:

var tableBodyCols = tableRows.children('td');

If you want only those for a specific row i:

var tableBodyCols = tableRows.eq(i).children('td');

where i will start from zero for the first row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.