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 :(
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.
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.
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()
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With