jQuery Traversing Descendants


In jquery, there are two useful jquery methods for traversing down the DOM tree. such as children() and find() jquery methods.

jQuery children() Method

The jQuery children() method is used to get the direct children of the specified element.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$("button").click(function(){
		$(".nav").children().css("border", "1px solid #000"); 
	});
});
</script>
</head>
<body>
<div class="box">
       <ul class="nav">
        	<li>List 1</li>
        	<li>List 2</li>
          	<li>List 3</li>
        	<li>List 4</li>
    	</ul>
   </div>
  <button>Click here</button>
</body>
</html>

jQuery find() Method

The jQuery find() method is used to get descendant elements of the specified element.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$("button").click(function(){
		$(".nav").find('a').css("color", "red"); 
	});
});
</script>
</head>
<body>
<div class="box">
       <ul class="nav">
        	<li><a href="#">List 1</a></li>
        	<li>List 2</li>
          	<li><a href="#">List 3</a></li>
        	<li>List 4</li>
    	</ul>
   </div>
  <button>Click here</button>
</body>
</html>