Lecture
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 }
Previous lessonMethods to Select HTML Elements - 1Next lessonCreating and Setting Attributes of HTML Elements
Lessons in this chapter · How does JavaScript work in the browser?
- 1. How Do Browsers Work?
- 2. DOM (Document Object Model)
- 3. Browser Window Object
- 4. Window - window.screen
- 5. Window - window.location
- 6. Methods to Select HTML Elements - 1
- 7. How to Select HTML Elements - 2
- 8. Creating and Setting Attributes of HTML Elements
- 9. Events
- 10. Advanced Event Handling
- 11. Multiple-choice quiz
- 12. JSON(JavaScript Object Notation)
- 13. Promise
- 14. Async/Await Handling Asynchronous Processes
- 15. Cookies
- 16. Multiple-choice quiz
- 17. JavaScript Summary
Quiz
0 / 1
What is the document.getElementsByClassName() method used to select?
All HTML elements
Elements with a specific ID
All elements with a specific class
Elements that satisfy a CSS selector
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help