Categories
JavaScript Answers

How to change element style attribute dynamically using JavaScript?

Spread the love

To change an element’s style attribute dynamically using JavaScript, you can directly access the style property of the element and modify its individual properties.

To do this, we write:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Element Style Attribute with JavaScript</title>
</head>
<body>

<div id="myElement" style="width: 100px; height: 100px; background-color: red;">This is my element</div>

<button onclick="changeStyle()">Change Style</button>

<script>
    function changeStyle() {
        var element = document.getElementById('myElement');
        
        // Change individual style properties
        element.style.width = '200px';
        element.style.height = '200px';
        element.style.backgroundColor = 'blue';
        element.style.color = 'white';
        element.style.fontSize = '20px';
    }
</script>

</body>
</html>

In this example, we have a <div> element with the id myElement and some initial styles set inline.

There’s a button with an onclick attribute calling the changeStyle() function when clicked.

Inside the changeStyle() function, we get the reference to the element using document.getElementById('myElement').

Then, we directly modify its style property to change its width, height, background color, text color, and font size.

You can adjust the style properties and values as needed within the changeStyle() function to achieve the desired visual changes.

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 *