jQuery width()

Introduction

Return the width of a <div> element:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>//from   www . j  a va 2s.co m
<script>
$(document).ready(function(){
  $("button").click(function(){
    document.getElementById("demo").innerHTML = "Width of div: " + $("div").width();
  });
});
</script>
</head>
<body>

<p id="demo"></p>
<div style="height:100px;width:300px;padding:10px;margin:3px;background-color:lightblue;">
</div><br>

<button>Display the width of div</button>

</body>
</html>

The width() method sets or gets the width of the selected elements.

As getter, the width() method returns the width of the first matched element.

As setter, the width() method sets the width of all matched elements.

Return the width:

$(selector).width()

Set the width:

$(selector).width(value)

Set the width using a function:

$(selector).width(function(index,current_width))
Parameter
Optional
Description
value
Required for setting width.
the width in px, em, pt, etc. Default unit is px
function(index,current_width)


Optional.


sets a function that returns the new width of selected elements
index - the index position of the element in the set
current_width - the current width of the selected element



PreviousNext

Related