Modifying Attributes and Classes
Use setAttribute and the classList API.
Attributes and Classes
Elements carry attributes (like href or data-id) and CSS classes. JavaScript gives you precise APIs to read and change both.
getAttribute
getAttribute reads an attribute’s value as a string, or returns null if it is absent.
const link = document.querySelector("a");
console.log(link.getAttribute("href"));All lessons in this course
- Changing Text and HTML Content
- Creating and Inserting Elements
- Modifying Attributes and Classes
- Removing and Replacing Nodes