Tutorials using JS
Change width of a Div in JavaScript
In this tutorial, you shall learn how to change width of a div element using JavaScript.
Solution
To set or change the width of a div element using JavaScript, we can use Element.style.width
property. Get the div element and set its style.width
property with the required length value.
divElement.style.width = '200px';
Program
When user clicks on the Click me
button, we get the div element with the id myDiv
and set its width to 200px
using style.width
property.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<div id="myDiv">About</div>
<style>
#myDiv {
width: 100px;
height: 100px;
background: green;
}
</style>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
//get the div element
const myDiv = document.getElementById("myDiv");
//set the width of the div
myDiv.style.width = '200px';
});
</script>
</body>
</html>