Javascript DOM HTML document images Collection get by index

Introduction

Get the URL of the first <img> element (index 0) in the document:

var x = document.images[0].src;

Click the button to display the URL of the first image (index 0) in the document.

View in separate window

<!DOCTYPE html>
<html>
<body>

<img src="image1.png" alt="flower" width="150" height="113">
<img src="image2.png" alt="flower" width="152" height="128">
<img src="image3.png" alt="Smiley face" width="42" height="42">
<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {/*ww  w .ja va2s  .co  m*/
  var x = document.images[0].src;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>



PreviousNext

Related