JavaScript – Change the Opacity of HTML Element

To change the opacity of a HTML Element using JavaScript, get reference to the HTML Element element, and assign required opacity value to the element.style.opacity property.

Opacity value ranges from 0 to 1. For example, 0.2, 0.3, 0.8, 0.45, etc., are some of the values that can be assigned to opacity property.

In the following example, we will change the opacity of HTML Element with id "myElement" to "0.2", in JavaScript, using element.style.opacity property.

example.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        #myElement {
            border:1px solid #CCC;
            width:100px;
            height:100px;
        }
    </style>
    <meta charset="utf-8">
</head> 
<body>
    <h2>Change Opacity of HTML Element in JavaScript</h2>
    <div id="myElement">Hello World!</div>
    <br>
    <button type="button" onclick="changeStyle()">Click Me</button>
    <script>
    function changeStyle(){
        var element = document.getElementById("myElement");
        element.style.opacity = "0.2";
    }
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to change the opacity of a HTML Element using JavaScript.