We can use jQuery to set the width of a div by using the jQuery width() method.

$("#div1").width(100);

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 jQuery width() method in the following JavaScript code.

$("#div1").width(200);

If you are using WordPress, don’t forget to change the $ to jQuery as below:

jQuery("#div1").width(200);

We can also set the width of a div using pure JavaScript with the width Property.

Example of Using jQuery 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 jQuery click() method to run a function when a user enters a new width.

We can use the val() method to get the new width the user has entered. We will then use the width() method to set the new width to #div2, based on what the user has entered.

Here is the code:

$("#click-me").click(function(){
  //Get the new width the user has entered
  var newWidth = Number($('#new-width').val());

  //Set the new width of #div
  $('#div2').width(newWidth);
});

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

Code Output:

Enter a new width below:

Change width

Full Code:


Enter a new width below:

Change width
<script> $("#click-me").click(function(){ var newWidth = Number($('#new-width').val()); $('#div2').width(newWidth); }); </script>

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

Categorized in:

jQuery,

Last Update: March 14, 2024