Is there a way to combine querySelectorAll with other DOM methods?
Answers:
Yes, you can combine
querySelectorAllwith other DOM methods to manipulate elements in a more advanced way.querySelectorAllreturns a NodeList of elements that match the specified CSS selector(s). You can then use methods such asforEach,Array.from, ormapto iterate over these elements and manipulate them as needed.Here are some examples of how you can combine
querySelectorAllwith other DOM methods:Example 1: Using
forEachto Iterate Over NodeList// Select all paragraphs and change their text color const paragraphs = document.querySelectorAll('p'); paragraphs.forEach((paragraph) => { paragraph.style.color = 'blue'; });Example 2: Using
Array.fromto Convert NodeList to Array// Select all div elements and create an array const divs = document.querySelectorAll('div'); const divArray = Array.from(divs); // Use map to create an array of their texts const texts = divArray.map(div => div.textContent); console.log(texts);Example 3: Combining with
for...of// Select all list items and log their inner text const listItems = document.querySelectorAll('li'); for (const item of listItems) { console.log(item.innerText); }Example 4: Filtering Elements
You can combine
querySelectorAllwithArray.prototype.filterto filter the selected elements based on some conditions:// Select all elements with a specific class and filter those with a specific attribute const items = document.querySelectorAll('.item'); const filteredItems = Array.from(items).filter(item => item.hasAttribute('data-active')); filteredItems.forEach(activeItem => { console.log(activeItem); });Example 5: Combining with
setTimeout// Select all buttons and change their background color after a delay const buttons = document.querySelectorAll('button'); setTimeout(() => { buttons.forEach(button => { button.style.backgroundColor = 'green'; }); }, 2000);Summary
By using
querySelectorAllin combination with other methods likeforEach,Array.from, or looping constructs, you can efficiently manipulate and work with groups of DOM elements based on your needs.