Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to locate all the descendant elements of a particular type of element?
The find( selector ) method can be used to locate all the descendant elements of a particular type of elements. The selector can be written using any selector syntax like element names, class names, IDs, or any valid CSS selector.
This method searches through the descendants of the matched elements in the DOM tree, constructing a new jQuery object from the matching descendant elements. It is different from the children() method as it searches through all levels of descendants, not just direct children.
Syntax
The basic syntax for the You can try to run the following code to learn how to locate all the descendant elements of a particular type of elements ? In this example, the The find()
$(selector).find(descendant-selector)
Example
<!DOCTYPE html>
<html>
<head>
<title>jQuery Find Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// Find all span elements inside p elements and apply styling
$("p").find("span").addClass("selected");
});
</script>
<style>
.selected {
color: blue;
font-weight: bold;
}
</style>
</head>
<body>
<p>This is first paragraph and <span>THIS IS BLUE</span></p>
<p>This is second paragraph and <span>THIS IS ALSO BLUE</span></p>
<div>This span <span>will not be affected</span> because it's not inside a p element</div>
</body>
</html>
find("span") method locates all <span> elements that are descendants of <p> elements and applies the "selected" class to them, making the text blue and bold.Conclusion
find() method is a powerful tool for traversing the DOM tree and selecting descendant elements based on any CSS selector, making it essential for dynamic content manipulation in jQuery.
