Modifying attributes, classes, and styles in the Document Object Model (DOM) is a common task in web development. JavaScript provides methods and properties to make these modifications. Below are examples demonstrating how to modify each of these aspects of the DOM.
-
Modifying Attributes:
You can use the
setAttribute and getAttribute
methods to modify and retrieve attributes, respectively.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Modify Attributes, Classes, and Styles</title> </head> <body> <img id="myImage" src="original-image.jpg" alt="Original Image"> <script> // Modifying the 'src' attribute const image = document.getElementById('myImage'); image.setAttribute('src', 'new-image.jpg'); // Retrieving the 'alt' attribute const altText = image.getAttribute('alt'); console.log('Alt Text:', altText); </script> </body> </html>
-
Modifying Classes:
You can use the
classList
property to add, remove, or toggle classes.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Modify Attributes, Classes, and Styles</title> <style> .highlight { background-color: yellow; } </style> </head> <body> <div id="myDiv">Hello, World!</div> <script> // Adding a class const myDiv = document.getElementById('myDiv'); myDiv.classList.add('highlight'); // Removing a class after a delay (e.g., 2 seconds) setTimeout(() => { myDiv.classList.remove('highlight'); }, 2000); </script> </body> </html>
-
Modifying Styles:
You can use the
style
property to directly modify inline styles.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Modify Attributes, Classes, and Styles</title> </head> <body> <div id="myElement">Change my style!</div> <script> // Modifying inline styles const myElement = document.getElementById('myElement'); myElement.style.color = 'blue'; myElement.style.fontSize = '20px'; </script> </body> </html>
These examples demonstrate basic ways to modify attributes, classes, and styles in the DOM using JavaScript. Depending on your application and requirements, you might use these methods in response to user interactions or other events.