Javascript DOM HTML document links Collection loop

Introduction

Loop through all links in the document, and output the URL (href) of each link:

Click the button to display the URL of each link in the document.

View in separate window

<!DOCTYPE html>
<html>
<body>

<img src ="image1.png" width="145" height="126" alt="Circle" usemap ="#myFlagMap">

<map name="myFlagMap">
  <area shape="rect" coords="0,0,30,30" href="https://java2s.com" alt="Site">
  <area shape="circle" coords="90,58,30" href="https://java2s.com" alt="Web">
  <area shape="circle" coords="50,50,40" href="https://www.java2s.com" alt="Target">
</map>/*from   ww w  .  java  2  s. co  m*/

<p>
  <a href="https://java2s.com">HTML</a><br>
  <a href="https://java2s.com">CSS</a>
</p>

<button type="button" onclick="myFunction()">Test</button>

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

<script>
function myFunction() {
  var x = document.links;
  var txt = "";
  var i;
  for (i = 0; i < x.length; i++) {
    txt = txt +  x[i].href + "<br>";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>



PreviousNext

Related