Can querySelectorAll() be used on a specific element rather than the whole document?
Answers:
Yes, the
querySelectorAll()method can be used on a specific element instead of the whole document. This allows you to search for descendant elements of that specific element, which can be useful for more targeted selections.Here’s a quick example:
<div id="parent"> <div class="child">Child 1</div> <div class="child">Child 2</div> <div class="child">Child 3</div> </div>You can select all elements with the class
childthat are descendants of theparentdiv like this:const parentElement = document.getElementById('parent'); const children = parentElement.querySelectorAll('.child'); // children will be a NodeList containing the three child divs children.forEach(child => { console.log(child.textContent); });In this example, the call to
querySelectorAll('.child')is made onparentElement, so it only returns the children inside that particular<div>. This method helps to narrow down the scope of your query and can improve performance when working with larger documents.