JAVASCRIPT
Selecting and Filtering DOM Elements by Criteria
Master advanced DOM selection using `querySelector` and `querySelectorAll`, then filter the results based on specific attributes or content with JavaScript.
// Select the first element matching a CSS selector
const firstParagraph = document.querySelector('p.intro');
if (firstParagraph) {
firstParagraph.style.backgroundColor = '#ffeebb';
}
// Select all elements matching a CSS selector
const allListItems = document.querySelectorAll('ul#myList li');
console.log('Total list items:', allListItems.length);
// Iterate and modify each selected element
allListItems.forEach((item, index) => {
item.textContent = `Item ${index + 1}: ${item.textContent}`;
if (index % 2 === 0) {
item.style.color = 'blue';
} else {
item.style.color = 'green';
}
});
// Filter elements based on content or attributes from a NodeList
const importantItems = Array.from(allListItems).filter(item =>
item.textContent.includes('important') || item.hasAttribute('data-highlight')
);
importantItems.forEach(item => {
item.style.fontWeight = 'bold';
item.style.border = '1px solid red';
});
// Example of HTML structure:
/*
<p class="intro">This is an introductory paragraph.</p>
<div>
<ul id="myList">
<li>First item</li>
<li data-highlight>Second important item</li>
<li>Third item</li>
<li>Fourth item with important text</li>
</ul>
</div>
*/
How it works: This snippet showcases powerful DOM element selection and filtering techniques. `document.querySelector()` retrieves the first element matching a CSS selector, while `document.querySelectorAll()` returns a static `NodeList` of all matching elements. The code then demonstrates iterating through this `NodeList` using `forEach()` to modify elements and converting it to an array with `Array.from()` to apply `filter()` based on text content or attribute presence, allowing for highly specific DOM manipulation.