width() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:width

Description

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

Parameter

ParameterRequire Description
valueRequired for setting width.Sets the width in px, em, pt, etc. Default unit is px
function(index,currentwidth) Optional. Sets a function that returns the new width of selected elements
  • index - Returns the index position of the element in the set
  • currentwidth - Returns the current width of the selected element

The following code shows how to Return the width of a <div> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        console.log("Width of div: " + $("div").width());
    });//  w  w w .  j  a v a 2s . co m
});
</script>
</head>
<body>

<div style="height:100px;width:300px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div><br>

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

</body>
</html>

Related Tutorials