Modifying Element Attributes And Properties
To modify an element’s attributes and properties with JavaScript, you can use the setAttribute() method and the dot notation respectively.
Example :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="myDiv" class="my-class" data-value="10">Hello, world!</div> </body> <script> // Get the element const myDiv = document.querySelector('#myDiv'); // Modify the attributes myDiv.setAttribute('id', 'newId'); myDiv.setAttribute('class', 'new-class'); myDiv.setAttribute('data-value', '20'); // Modify the properties myDiv.textContent = 'Goodbye, world!'; myDiv.id = 'newerId'; myDiv.className = 'newer-class'; myDiv.dataset.value = '30'; </script> </html>
Output :

Explanation :
In the example above, we first select the element with the ID myDiv using the querySelector() method. Then, we modify the attributes using the setAttribute() method, and the properties using the dot notation. Note that the data-* attribute is accessed using the dataset property.
No Comment! Be the first one.