In this blog post, we will learn how to use jQuery’s equivalent of the
querySelectorAll function, which is used to select multiple elements based on a given
CSS selector.
What is QuerySelectorAll?
The querySelectorAll() method is a JavaScript function that returns a NodeList containing all
elements in the document that match the specified CSS selector(s). This is a powerful function that allows web
developers to quickly and efficiently target and manipulate elements on a webpage.
Using QuerySelectorAll in jQuery
Although jQuery doesn’t have a direct equivalent of querySelectorAll, you can achieve similar
functionality using the jQuery() function, also known as the $() function.
To use the jQuery() function, simply pass your desired CSS selector as a parameter. This
function will return a jQuery object containing all the elements that match the specified selector, which you
can then manipulate using jQuery methods.
Here is an example:
$(document).ready(function () { // Select all the elements with class 'my-class' const myElements = $(".my-class"); // Change the background color of the selected elements myElements.css("background-color", "red"); });
Examples of QuerySelectorAll in jQuery
Let’s look at a few more examples to get a better understanding of how to use the jQuery() function:
Example 1: Selecting elements by tag name
Select all the <p> elements and change their font size:
$(document).ready(function () { const allParagraphs = $("p"); allParagraphs.css("font-size", "18px"); });
Example 2: Selecting elements by class
Select all elements with the class ‘highlight’ and change their background color:
$(document).ready(function () { const highlightedElements = $(".highlight"); highlightedElements.css("background-color", "yellow"); });
Example 3: Selecting elements by ID
Select an element with the ID ‘my-element’ and change its text:
$(document).ready(function () { const myElement = $("#my-element"); myElement.text("This is the new text!"); });
Conclusion
While jQuery doesn’t have a direct equivalent for the querySelectorAll function, you can
achieve the same functionality using the jQuery() or $() function. This
allows you to select multiple elements based on CSS selectors and manipulate them using jQuery’s powerful
methods.