Javascript DOM HTML document links Collection get by index

Introduction

Get the URL of the first link (index 0) in the document:

var x = document.links[0].href;

Click the button to display the URL of the first link (index 0) 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 .ja  v a  2  s  . co m*/

<p>
  <a href="https://java2s.com">HTML</a><br>
  <a href="https://java2s.com">CSS</a>
</p>
<button onclick="myFunction()">Test</button>

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

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

</body>
</html>



PreviousNext

Related