1. Home
image

jQuery Tutorial Concepts - From Beginner to Pro

Learn jQuery from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 19
  • 3
right-top-arrow
18

jQuery find() Method

Updated on 12/09/2024447 Views

jQuery find() method efficiently traverses the Document Object Model (DOM) tree. It accepts a selector as input and searches for descendant elements of the selected element(s) that match the specified criteria. These elements can be a child, grandchildren, etc.

The syntax for a jQuery find method is given by:$(selector).find(filter)

In this context, "selector" represents the chosen elements from which all descendant elements will be located.

Parameters: This method doesn't require any parameters.

Return Value: It provides all descendant elements of the selected element.For more info about element selection with jQuery find() refer to jQuery’s .find() API Documentation.

Functionality

Some of the functionalities of the jQuery find method are detailed below:

Input

The find() method accepts a single argument, which can be a selector string, a jQuery object, or a DOM element. For selector strings, the format mirrors that of the $() function enabling the precise targeting of elements by ID, class, or tag name.

Traversal

Unlike its counterpart, .children(), find() doesn't limit itself to direct children; instead, it goes deep into the DOM tree, exploring all descendants—children, grandchildren, and beyond.

Output

Upon execution, find() returns a new jQuery object containing the descendant elements that match the provided selector, ready for further manipulation.

Identifying Elements with jQuery find Element

In jQuery, it's quite easy to find an element by its ID using the find() method along with the ID selector. Provided below are some examples:

Example 1: jQuery find element by id

Locate all <span> elements within a <div> with the ID "container," employing a selector string.

$("#container").find("span");

Example 2: Identify all elements with the class "clickable" that are descendants of the currently selected elements, utilizing a class selector.

$(".clickable").find("*");

Example 3: Utilize find() with another jQuery object as input, assuming the object represents a specific element.

var $specificElement = $("#specificElement");

$specificElement.find(".sub-element");

Example 4: jQuery find element by attribute

Elements can be found by attribute using the find() method along with the attribute selector. Let us understand this.

Assume that we have the following HTML:

<div id="container">

<p data-type="paragraph">First paragraph</p>

<p data-type="paragraph">Second paragraph</p>

<p data-type="footer">Footer paragraph</p>

</div>

Now, if someone wants to find all paragraphs with the attribute: data-type="paragraph", they may use the following jQuery code:

var paragraphs = $("#container").find("[data-type='paragraph']");

This code will select the paragraphs with the data-type attribute set to "paragraph" within the element with the ID "container".The syntax is:var elements = $("parentElement").find("[attributeName='attributeValue']");

Essentially, this will find elements within the "parentElement" that have the specified attribute name and value.

Example 5: jQuery find element with data attribute

In jQuery, one can use the find() method to locate elements with specific data attributes. For instance, if you have HTML elements with data attributes like data-id, data-type, etc., you can find them using jQuery.Check out the example provided below:

Given this HTML file:<div id="container">

<div data-id="1">Element 1</div>

<div data-id="2">Element 2</div>

<div data-id="3">Element 3</div>

</div>

Now, to find elements with a specific data attribute, we can utilize the following jQuery code:

var elementsWithDataAttribute = $("#container").find("[data-id]");NOTE: The jQuery find data attribute refers to using the .find() method to locate elements based on their data attributes within a selected element. This allows for targeted searching and manipulation of elements with specific data attributes.

Finding Multiple Descendants of a Given Selector

Let’s understand the methods for finding multiple descendants of a given selector by some examples.

Example 1:<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>jQuery Find Example</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>

$(document).ready(function(){

// Select the parent element

var parentElement = $("#parent");

// Find all descendants with class "child" within the parent element

var descendants = parentElement.find(".child");

// Iterate over the found elements and apply styles

descendants.each(function(){

$(this).css("color", "red");

});

});

</script>

</head>

<body>

<div id="parent">

<div class="child">First Child</div>

<div class="child">Second Child</div>

<div>

<div class="child">Third Child</div>

</div>

</div>

</body>

</html>

In this example:

  • We have a parent element with the ID parent.
  • Inside the parent element, there are multiple descendant elements with the class child.
  • Using jQuery's find() method, we select all elements with the class child that are descendants of the parent element.
  • We then iterate over the found elements using each() and apply a CSS style to change their text color to red.

Example 2:

Here is another example of selecting multiple elements in jQuery:<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>jQuery Find Example</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>

$(document).ready(function(){

// Select multiple elements using comma-separated selectors

var elements = $("#parent .child, #anotherParent .child");

// Apply styles to the selected elements

elements.css("color", "blue");

});

</script>

</head>

<body>

<div id="parent">

<div class="child">First Child</div>

<div class="child">Second Child</div>

</div>

<div id="anotherParent">

<div class="child">Third Child</div>

<div class="child">Fourth Child</div>

</div>

</body>

</html>

In this example:

  • We have used a comma-separated list of selectors (#parent .child, #anotherParent .child) to select elements with the class child that are descendants of elements with the IDs parent and anotherParent.
  • We then apply a CSS style to change the text color of the selected elements to blue.

Example 3:

Let us see a similar example:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>jQuery Find Example</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>

$(document).ready(function(){

// Find all divs, uls, and ps descendants of #div1 and apply CSS styles

$("#div1").find("div, ul, p").css({"color": "red", "border": "6px dashed red"});

});

</script>

</head>

<body>

<div id="div1">

<div>This is a div</div>

<ul>

<li>This is a list item</li>

</ul>

<p>This is a paragraph</p>

</div>

</body>

</html>

In this example:

  • We select the element with the ID div1.
  • We use the find("div, ul, p") method to select all descendant div, ul, and p elements of #div1.
  • We then apply CSS styles to change the text color to blue and add a blue dashed border with a width of 6 pixels to all selected descendant elements.

This showcases the versatility of the find() method in targeting various types of elements within a parent element and manipulating their styles collectively.

Key Points

Let’s summarize the details regarding the jQuery find method. The main points are:

  • find() searches all descendant elements, offering a broader scope compared to .children(), which focuses solely on direct children.
  • The selector argument can target elements by ID, class, tag name, or a combination thereof, granting flexibility in the search criteria.
  • The resultant jQuery object from find() facilitates the manipulation of the discovered elements, enabling cascading actions.
  • jQuery doesn't have its class system; it utilizes CSS classes for element selection.
  • One may combine class selectors with other selectors (e.g., ID selectors, tag names) for more complex element selection.

Additional Considerations

While exploring the find() method, it's worth mentioning the potential of the universal selector (*) to uncover all descendant elements, though prudent usage is advised due to performance implications. Moreover, hinting at method chaining illustrates the capability to construct intricate queries, paving the way for sophisticated DOM manipulation.

Conclusion

In summation, the jQuery find() method emerges as a formidable ally in the realm of DOM traversal and manipulation within jQuery. jQuery's ability to navigate through descendant elements and its easy syntax allows developers to create dynamic web experiences with precision. Understanding CSS classes and jQuery selectors helps navigate and manipulate webpage structures effectively.

FAQs

1. How to find a class using jQuery?
You can find elements with a specific class in jQuery using a period (".") followed by the class name. For example, $(".myClass") selects all elements with the class "myClass". The "jQuery find class" refers to using the jQuery .find() method to locate elements with a specific class within a selected element.You can also use the .find() method to find classes within other elements.

2. How to check if a class is in jQuery?
We can use the hasClass() method to determine if a specific class is applied to a selected element.
For example:

if ($("h1").hasClass("important")) {
console.log("This h1 has the class 'important'");
} else {
console.log("This h1 does not have the class 'important'");
}
3. How to search for class names in jQuery?
In jQuery, you can search for elements using .find() with a class selector: Pass a string starting with a period (.) representing the class you want to find. Here's how you can do it:

var clickableElements = $("#content").find(".clickable");

clickableElements.each(function() {

console.log($(this).text());

});

This will search for all descendant elements (children, grandchildren, etc.) within the element with ID "content" that have the class "clickable".

4. How to find a class in JavaScript?
While jQuery offers convenient methods for DOM manipulation, JavaScript itself also provides ways to find elements by class. A common method for this is using the querySelector() method. This method returns a NodeList containing all matching elements based on the class selector. Here’s an example:var clickableElements = document.querySelectorAll(".clickable");

// Loop through the NodeList

clickableElements.forEach(function(element) {

element.addEventListener("click", function() {

// Code to handle click event

});

});

5. How to find and add a class in jQuery?
In jQuery, you can find elements with a specific class using the find() method and then add a class to them using the addClass() method.
Here's how you can do it:var elementsWithClass = $('#container').find('.example');
// Add a new class 'new-class' to each found element
elementsWithClass.addClass('new-class');

6. What is the class in jQuery?
In jQuery, a class is a style or behavior applied to HTML elements. It can be selected, added, removed, or checked using jQuery methods for dynamic webpage manipulation.

mukesh

mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...