Sunday 30 September 2018

JavaScript: setAttribute: Set the value associated with attribute

setAttribute() method is used to set the value associated with the attribute.

Syntax
element.setAttribute(attribute, value);

setAttribute.html
<!DOCTYPE html>

<html>

<head>
    <title>Set Attribute</title>

    <style type="text/css">
        .color1 {
            color: red;
            font-size: 3em;
        }
        
        .color2 {
            color: green;
            font-size: 5em;
        }
    </style>

</head>

<body>
    <p class="color1" id="para1">
        Good Morning
    </p>

    <script>
        var element = document.getElementById("para1");
        confirm("Press OK");
        element.setAttribute("class", "color2");
    </script>
</body>

</html>

By default, text displayed in red color, once you press OK, it change the class attribute value to ‘color2’, as per styles text change its color to green.


Previous                                                 Next                                                 Home

No comments:

Post a Comment