Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find all elements with class beneath parent, even in children elements

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")?

like image 748
Ben Avatar asked Jul 14 '15 14:07

Ben


People also ask

Can we get the children element from the parent element using jQuery?

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.

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.

How do you get children of children 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.

What is $() in jQuery?

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.


1 Answers

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>
like image 152
AmmarCSE Avatar answered Oct 20 '22 07:10

AmmarCSE