Javascript Reference - HTML DOM Image width Property








The width attribute specifies the width of an image.

The width property sets or gets the value of the width attribute of an image.

Browser Support

The width property is supported in all major browsers.

width Yes Yes Yes Yes Yes

Syntax

Return the width property.

var v = imageObject.width

Set the width property.

imageObject.width=pixels

Property Values

Value Description
pixels The width in pixels




Return Value

A Number type value representing the width of the image in pixels.

Example

The following code shows how to get the width of an image.


<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" width="100" height="100">
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from  w ww . jav a 2  s  . c  o  m-->
    var x = document.getElementById("myImg").width;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to change the height and width of an image to 300px.


<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" width="100" height="100">
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from w ww .  j a v a  2s.  c  o m-->
    document.getElementById("myImg").height = "300";
    document.getElementById("myImg").width = "300";
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to get the width of an image styled with CSS.


<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" style="width:100px;height:100px;">
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from   w w w  .  j av  a 2 s.c o m-->
    var x = document.getElementById("myImg").width;
    document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 4

The following code shows how to change the width of an image to 300px.


<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" width="100" height="100">
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--   ww  w.  j a  v  a2  s. c o m-->
    document.getElementById("myImg").width = "300";
}
</script>

</body>
</html>

The code above is rendered as follows: