Here is some sample HTML:
<div class="parent">
<div class="searchEl"></div>
<div class="searchEl"></div>
<div class="child">
<div class="searchEl"></div>
<div class="searchEl"></div>
</div>
</div>
And here is a jQuery function:
$(function(){
$(".parent>.searchEl").each(function(){
$(this).html("Found this one");
});
});
The DOM elements will end up like so:
<div class="parent">
<div class="searchEl">Found this one</div>
<div class="searchEl">Found this one</div>
<div class="child">
<div class="searchEl"></div>
<div class="searchEl"></div>
</div>
</div>
Using jQuery/Javascript, how can I search for and find all the elements with class .searchEl
beneath the element .parent
, even if they are within another child element, without searching the document globally with $(".searchEl")
?
jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.
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.
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.
In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: 1. $( "div.
Use a space instead of >
$(function() {
$(".parent .searchEl").each(function() {
$(this).html("Found this one");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="parent">
<div class="searchEl"></div>
<div class="searchEl"></div>
<div class="child">
<div class="searchEl"></div>
<div class="searchEl"></div>
</div>
</div>
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