Query Traversing - Descendants (find method) using jQuery in Tamil


In jQuery, the find() method is commonly used for Query Traversing to locate descendant elements within the selected set of elements. Unlike children(), the find() method searches through all levels of descendants, allowing you to select elements that are not necessarily immediate children. It's particularly useful for selecting nested elements at any level within a parent element.



find() Method

The find() method in jQuery is used to search for descendant elements that match the specified selector within the selected elements.

Syntax

$(selector).find(filter)

selector : A string containing a selector expression to match the descendants against.

filter : A string containing a filter expression to narrow down the selection of descendants (optional).

Keypoints

  • The find() method is more versatile than children() as it searches for descendants at any level.
  • If no selector is provided, all descendants are selected.
  • The filter parameter is optional and can be used to further refine the selection based on a specific condition.

Source Code

  • $('ul.list').find('li') selects all <li> elements that are descendants of the unordered list with the class 'list'. This includes both the immediate children (Graphic Designing, Web Designing, Programming) and the nested <li> elements within the second <li> (C Program, C++ Program, Java, C#).
  • .css('color','green') sets the text color of the selected elements to green.
  • The jQuery code will change the text color of all list items (<li>) within the unordered list with the class 'list' to green. This includes both the immediate children and the nested <li> elements within the second <li>. The CSS style setting the text color to black for all list items is overridden by the jQuery code.
<html>
	<head>
		<title>DOM Query</title>
		<style>
			li{color:black;}
		</style>
	</head>
	<body>
	<h3>Find Elements</h3>
	<ul class='list'>
		<li>Graphic Designing</li>
		<li>Web Designing</li>
		<li>Programming</li>
		<li>
			<ul>
				<li>C Program</li>
				<li>C++ Program</li>
				<li>Java</li>
				<li>C#</li>
			</ul>
		</li>
	</ul>
	<script src="js/jquery.js"></script>
	<script>
		$("document").ready(function(){
			$('ul.list').find('li').css('color','green');
		});
	</script>
	</body>
</html>

Here's how the find() method can be used to select elements within nested structures, making it a powerful tool for traversing and manipulating the DOM in jQuery.