Selecting HTML Elements - 2
getElementsByClassName
document.getElementsByClassName()
is a method used to select all elements in HTML that have a specific class
attribute.
Imagine you want to find all products of a specific brand in a store. The class
is like the brand, used to group multiple elements with the same style or functionality.
HTML elements with the same class
<div class="highlighted">div element</div>
<p class="highlighted">p element</p>
<span class="highlighted">span element</span>
JavaScript: Select all elements with class 'highlighted'
const highlightedElements = document.getElementsByClassName('highlighted');
for (let elem of highlightedElements) {
elem.style.backgroundColor = 'yellow'; // Change the background color of emphasized elements to yellow
}
querySelectorAll
document.querySelectorAll()
is a method that uses CSS selectors to select one or multiple elements on a web page.
querySelectorAll allows you to specify multiple conditions to select elements precisely.
HTML: HTML elements with various classes
<div class="box red">Red box</div>
<p class="text blue">Blue text</p>
<span class="highlight red">Red highlighted text</span>
JavaScript: Select all elements with class 'red'
const redElements = document.querySelectorAll('.red');
for (let elem of redElements) {
elem.style.border = '2px solid red'; // Add a red border
}
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.