child") with variables For example, I have a
includeig other
and the first one is selected, and it ...">

Jquery: use ("parent> child") with variables

For example, I have a <div class="first"> includeig other <div> and the first one is selected, and it injected it into a variable

 variable = $('div.first') 

And now I want something like this

 $(variable + " > div") 

I know this seems silly, but what if I had an array containing the rows of the table and I need to access the columns inside a specific row:

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

Use .children()

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

Or a context selector:

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

Both are equivalent, but the first is easier to read imho.

Here is a fiddle showing both.


And to repeat all sets of children of each row in the table:

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

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

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

The fiddle is updated here.

+14
source

You cannot do $(variable + " > div") because variable not a string, but a jquery element.

But you can try:

 variable.children("div"); 
+1
source

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

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

If you really have more than one td level, use

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

or use your own dom object:

  var tableBodyCols = tableRows[i].cells; 
0
source

If you need all the <td> cells, use:

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

If you want to use only those for a specific line i :

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

where i will start from zero for the first line.

0
source

All Articles