The Image object represents an HTML <img> element.
The Image object supports the standard properties and events.
Property | Description |
---|---|
align | Not supported in HTML5.
Use style.cssFloat instead. Sets or gets the align attribute of an image |
alt | Sets or gets the alt attribute of an image |
border | Not supported in HTML5.
Use style.border instead. Sets or gets the border attribute of an image |
complete | Returns whether the browser is finished loading an image |
crossOrigin | Sets or gets the CORS settings of an image |
height | Sets or gets the height attribute of an image |
hspace | Not supported in HTML5.
Use style.margin instead. Sets or gets the hspace attribute of an image |
isMap | Sets or gets whether an image should be part of a server-side image-map |
longDesc | Not supported in HTML5. Sets or gets the longdesc attribute of an image |
name | Not supported in HTML5. Use id instead. Sets or gets the name attribute of an image |
naturalHeight | Returns the original height of an image |
naturalWidth | Returns the original width of an image |
src | Sets or gets the value of the src attribute of an image |
useMap | Sets or gets the usemap attribute of an image |
vspace | Not supported in HTML5.
Use style.margin instead. Sets or gets the vspace attribute of an image |
width | Sets or gets the width attribute of an image |
We can access an <img> element by using getElementById().
<!DOCTYPE html>
<html>
<body>
<img id="myImg" src="http://java2s.com/style/demo/border.png" alt="test" width="100" height="100">
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from w w w . j a v a 2 s .co m-->
var x = document.getElementById("myImg").src;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
The code above is rendered as follows:
We can create an <img> element by using the document.createElement() method.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<!-- www .ja v a 2s . c o m-->
<script>
function myFunction() {
var x = document.createElement("IMG");
x.setAttribute("src", "http://java2s.com/style/demo/border.png");
x.setAttribute("width", "100");
x.setAttribute("width", "100");
x.setAttribute("alt", "border image");
document.body.appendChild(x);
}
</script>
</body>
</html>
The code above is rendered as follows: