본문으로 건너뛰기

HTML Element Selection Techniques - 2

HTML Element Selection Techniques - 2

getElementsByClassName

document.getElementsByClassName() is a method for selecting all elements in HTML that have a certain class attribute.

Analogy: Imagine you want to find all products of a certain brand in a store. The class is like that brand, grouping several elements together with the same style or function.

Code Example:
<!-- Multiple elements with a class in HTML -->
<div class="highlighted">First Box</div>
<p class="highlighted">This is highlighted text.</p>
<span class="highlighted">This is also highlighted!</span>
// Selecting all elements with class="highlighted" using JavaScript
let 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 for selecting one or multiple elements on a web page using CSS selectors.

Analogy: If you wanted to find products in a store that match a specific color, brand, and size simultaneously? querySelectorAll allows you to specify multiple criteria at once to precisely select the elements you want.

Code Example:
<!-- Multiple elements in HTML -->
<div class="box red">Red Box</div>
<p class="text blue">Blue Text</p>
<span class="highlight red">Highlighted Red Text</span>
// Selecting all elements with the class "red" using JavaScript
let redElements = document.querySelectorAll('.red');
for (let elem of redElements) {
elem.style.border = '2px solid red'; // Adding a red border
}

Conclusion

Web page elements can have various features and styles. By using methods like getElementsByClassName and querySelectorAll, you can easily find elements that match your desired criteria. These tools enable you to create more diverse web pages and provide better experiences for users!