How to hide child elements in jQuery

Assume you have a parent element with multiple child elements. On some event such as a button click, you want to hide all the children of this element at once using jQuery.
Suppose the page structure is as given below.

<!– parent element –>
<div id=”parent”>
     <!– Child elements –>
     <div>Child One</div>
     <div>Child Two</div>
     <div>Child Three</div>
</div>
<button onclick=”hideChildren();”>Hide</button>

Above HTML code contains a div with id parent with three child div elements. It also contains a button which when clicked shall hide all the three child elements. Note that button click calls a hideChildren function which we will be writing in this post.


An element in jQuery can be hidden using hide function. We need to call this function on child elements(or div in this case). There are following two ways in which all child elements can be selected.

Method 1: Using children function
children function when called on an element returns all its child elements. Calling hide on these elements will hide all child elements. Thus,

<script type="text/javascript">
   function hideChildren() {
      // select all children and hide them
      $("#parent").children().hide();
   }
</script>

Note that hideChildren is called when button is clicked.
children function can also accept a selector. In that case, it will only select child elements matching that selector. Example, $("#parent").children(".green") will select only those child elements which have a class green. From jQuery docs of children,

Get the children of each element in the set of matched elements, optionally filtered by a selector.

Method 2: Using find function
find function accepts a string which represents the selector for an element. find function when called on an element searches for its child elements that match with the given selector.
Example, $("#check").find("input.green") will search for all input elements having class green and which are children of element having id as check.

Learn various methods to select an element in jQuery here.

From jQuery docs of find,

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Coming back to our example, child elements can be hidden using find as shown below.

<script type="text/javascript">
   function hideChildren() {
      // select all child divs and hide them
      $("#parent").find("div").hide();
   }
</script>

Note that hideChildren is called when button is clicked. Also, remember that this method will only hide child elements with div tag. Any other child elements will still be visible since find function will only select div elements. Thus, this method can be used for hiding selective child elements.

Keep visiting for more!!!

 

0

Mark Your Impression

Close Menu