Can querySelectorAll() be used with class names?
Answers:
Yes,
querySelectorAll()can be used with class names in JavaScript. This method allows you to select multiple elements in the DOM that match a specified CSS selector. When using class names, you can target elements by their class in the following way:const elements = document.querySelectorAll('.className');In this example, replace
.classNamewith the actual class name you're targeting. The dot (.) before the class name indicates that you're selecting by class.Here is a simple example of how to use it:
<div class="example">Item 1</div> <div class="example">Item 2</div> <div class="example">Item 3</div>const elements = document.querySelectorAll('.example'); elements.forEach(element => { console.log(element.textContent); });This code will select all
<div>elements with the classexampleand log their text content to the console.Additionally, you can use more complex selectors with
querySelectorAll(). For example, if you want to select all<div>elements with the classexamplethat are inside another element with a specific ID, you could do it like this:const elements = document.querySelectorAll('#parentId .example');This effectively combines different selectors to narrow down your selection criteria.