Traversing Down the DOM Tree with jQuery

This article discusses useful jQuery methods for traversing down the DOM tree.
 

Traversing Down the DOM Tree

Lets refer the following html structure :


<div class="block">div
  <p class="block">p
    <span class="block">Hello</span>
  </p>
</div>

 
In the above code, “span” element is child of “p” which in turn is the child of “div”
 
Traversing Up the DOM Tree using jQuery

jQuery methods for traversing down the DOM treee

 
Following methods are helpful for traversing down the DOM tree :

– children() method
– find() method

 

children() method

 
jQuery children() method traverses the child nodes of the element as specified in the selector expression.

The children() method descends exactly one level in the DOM tree to select the immediate children.

Example :


$('div').children()

We can also chain this method for find grand-children of an element ;

Example :


$('div').children().children()

 

Program using children() method

 

<!DOCTYPE html>
<html>
<head>
<style>
.block {
  display: block;
  border: 1px solid black;
  padding: 10px;
  color:black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
  //Change children color
  $("div").children().css( "color", "red");
  $("div").children().children().css("color", "green");
});
</script>
</head>
<body>
<div class="block">div
  <p class="block">p
    <span class="block">Hello</span>
  </p>
</div>
</body>
</html>

 

find() method

 
jQuery find() method finds elements in DOM tree. It finds elements by descending the entire depth of document to match the element.

Example :


$('body').find('div')

We can also pass a jQuery object to the find() method.

Example :


$('body').find($('div'))

 

Program using find() method

 

<!DOCTYPE html>
<html>
<head>
<style>
.block {
  display: block;
  border: 1px solid black;
  padding: 10px;
  color:black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
  //Find "p" under "div"
  $("div").find("p").css({
    "color": "red",
    "border": "1px solid red"
  });
});
</script>
</head>
<body>
<div class="block">div
  <p class="block">p
    <span class="block">Hello</span>
  </p>
</div>
</body>
</html>

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags