Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: use (“parent > child”) with variables

Tags:

jquery

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 :(
like image 991
Timofey Trofimov Avatar asked Apr 02 '13 12:04

Timofey Trofimov


People also ask

How to target parent element in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

What is the use of parent () and child () method in jQuery?

It is a jQuery Selector used to select all elements that are the direct child of its parent element. Parameter Values: parent: Using this, the parent element will be selected. child: Using this, the direct child element of the specified parent element will be selected.

What is parent () parent () jQuery?

The parent() is an inbuilt method in jQuery which is used to find the parent element related to the selected element. This parent() method in jQuery traverse a single level up the selected element and return that element. Syntax: $(selector).parent()

How to get child element in jQuery?

jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.


1 Answers

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.

like image 112
Fabrício Matté Avatar answered Oct 05 '22 16:10

Fabrício Matté