How to Select HTML Elements - 2
getElementsByClassName
document.getElementsByClassName()
is a method used to select all elements in HTML with a specific class
attribute.
Imagine you're in a store and want to find all products of a certain brand. A class
is like that brand, used to group multiple elements with the same style or function.
Multiple 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: Selecting All Elements with the Class 'highlighted'
const highlightedElements = document.getElementsByClassName('highlighted');
for (let elem of highlightedElements) {
elem.style.backgroundColor = 'yellow'; // Changing the background color of highlighted elements to yellow
}
querySelectorAll
document.querySelectorAll()
is a method that uses CSS selectors to select one or multiple elements in a web page.
querySelectorAll allows you to specify multiple conditions simultaneously to precisely select the elements you want.
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: Selecting All Elements with the Class 'red'
const redElements = document.querySelectorAll('.red');
for (let elem of redElements) {
elem.style.border = '2px solid red'; // Adding a red border
}
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.