Javascript DOM HTML document images Collection loop

Introduction

Loop through all <img> elements in the document, and output the URL (src) of each image:

Click the button to display the URL of each img element 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 type="button" onclick="myFunction()">Test</button>

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

<script>
function myFunction() {/*from  w  w  w . j  a  va2s.co m*/
  var x = document.images;
  var txt = "";
  var i;
  for (i = 0; i < x.length; i++) {
    txt = txt +  x[i].src + "<br>";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>



PreviousNext

Related