We can use JavaScript to set the width of a div by using the Style width Property.

document.getElementById("div1").style.width = "100px";

Let’s take a look at a simple example below.


Let’s say we have the following HTML:

This paragraph is in a div that we want to set the width of.

If we want to set the width of #div1 to say 200px, we will use the width Property in the following JavaScript code.

document.getElementById("div1").style.width = "200px";

We can also set the width of a div using jQuery with the jQuery width() method.

Example of Using JavaScript to Set the Width of a Div

In this example, we will have a simple div with a background color. The width of the div will be 100px. We will have an input field that will allow the user to enter a new width for the div. Here is the HTML code.


Enter a new width below:

Change width

We can utilize the onclick event to run a function when a user enters a new width.

We can also use the value property to get the new width the user has entered. We will then use the width Property to set the new width to #div2, based on what the user has entered.

Here is the code:

function changeWidth(){
  //Get the new width the user has entered
  var newWidth = Number(document.getElementById("new-width").value) + "px";

  //Set the new width of #div
  document.getElementById('div2').style.width = newWidth;
};

The final code and output for setting the width of a div using JavaScript is below:

Code Output:

Enter a new width below:

Change width

Full Code:


Enter a new width below:

Change width
<script> function changeWidth(){ var newWidth = Number(document.getElementById("new-width").value) + "px"; document.getElementById('div2').style.width = newWidth; }; </script>

Hopefully this article has helped you to understand how to use JavaScript to set the width of a div.

Categorized in:

JavaScript,

Last Update: March 14, 2024