Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between width and innerWidth in jQuery?
Width in jQuery refers to the horizontal measurement of an element's content area. The width() method returns or sets the width of an element, excluding padding, border, and margin.
innerWidth in jQuery returns the inner width of an element, which includes the content width plus the left and right padding, but excludes the border and margin.
Key Differences
The main difference between width() and innerWidth() is ?
- width() ? Returns content width only (excludes padding, border, margin)
- innerWidth() ? Returns content width + padding (excludes border, margin)
Example - width() Method
The following example demonstrates how to get the width of an element using width() method ?
<!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(){
alert("Width of div element: " + $("div").width());
});
});
</script>
</head>
<body>
<div style="height:200px;width:400px;padding:20px;margin:1px;border:1px solid red; background-color:gray;"></div><br>
<button>Get Width of div</button>
</body>
</html>
The output of the above code is ?
Width of div element: 400
Example - innerWidth() Method
The following example shows how to get the inner width using innerWidth() method ?
<!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(){
alert("Inner Width of div element: " + $("div").innerWidth());
});
});
</script>
</head>
<body>
<div style="height:200px;width:400px;padding:20px;margin:1px;border:1px solid red; background-color:gray;"></div><br>
<button>Get Inner Width of div</button>
</body>
</html>
The output of the above code is ?
Inner Width of div element: 440
Notice that innerWidth() returns 440px (400px content + 20px left padding + 20px right padding), while width() returns only 400px.
Conclusion
Use width() when you need the content area width only, and innerWidth() when you need the content width including padding.
