Categories
JavaScript Answers

How to add or update an attribute to an HTML element using JavaScript?

Spread the love

To add or update an attribute to an HTML element using JavaScript, you can use the setAttribute() method to add a new attribute or update an existing one, and the getAttribute() method to retrieve the value of an attribute.

Here’s an example of how to add or update an attribute to an HTML element using JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Attribute</title>
</head>
<body>
    <div id="myDiv">Hello, World!</div>

    <script>
        // Get the element by its ID
        var element = document.getElementById("myDiv");

        // Add or update an attribute
        element.setAttribute("class", "newClass");

        // Get the value of the attribute
        var className = element.getAttribute("class");
        console.log("Class name:", className); // Output: Class name: newClass
    </script>
</body>
</html>

In this example, the JavaScript code adds or updates the class attribute of the <div> element with the ID myDiv to "newClass". Then, it retrieves the value of the class attribute using the getAttribute() method and logs it to the console.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *