Q. Explain querySelectorAll() in Javascript
querySelectorAll()
is another JavaScript method used for selecting elements from the DOM (Document Object Model), similar to querySelector()
. However, instead of returning just the first matching element, querySelectorAll()
returns a static NodeList containing all elements within the document that match the specified CSS selector.
Here's how you use it:
javascriptconst elements = document.querySelectorAll(selector);
selector
is a CSS selector string specifying the criteria for selecting the desired element(s), just like withquerySelector()
.elements
will hold a NodeList, which is an array-like collection of elements that match the given selector. If no elements match the selector, an empty NodeList is returned.
You can then iterate over the NodeList to access each matching element individually, or use array methods like forEach()
to perform operations on each element.
For example:
html<!DOCTYPE html>
<html>
<head>
<title>querySelectorAll Example</title>
</head>
<body>
<div id="container">
<p class="text">First paragraph</p>
<p class="text">Second paragraph</p>
<p class="text">Third paragraph</p>
</div>
<script>
// Select all paragraphs with the class "text"
const paragraphs = document.querySelectorAll('.text');
// Iterate over the NodeList and log the text content of each paragraph
paragraphs.forEach(paragraph =>
{
console.log(paragraph.textContent);
});
</script>
</body>
</html>
In this example, document.querySelectorAll('.text')
selects all paragraph elements with the class "text"
and stores them in the paragraphs
variable as a NodeList. Then, we iterate over this NodeList using forEach()
and log the text content of each paragraph to the console.
No comments:
Post a Comment