HTML DOM links Collection


The links Collection returns a list/collection of all the links corresponding to <a> and/or <area> elements.

Syntax

Following is the syntax −

Returning links collection

document.links

Properties

Here, “links” collection can have the following properties and methods −

Property/MethodDescription
lengthIt returns the number of <a> and <area> elements</a>
namedItem()It returns the <a> or/and <area> element with the specified id</a>

Example

Let us see an example for links collection length property −

 Live Demo

<!DOCTYPE html>
<html>
<head>
<title>Links Collection length</title>
<style>
   form {
      width:70%;
      margin: 0 auto;
      text-align: center;
   }
   * {
      padding: 2px;
      margin:5px;
   }
   input[type="button"] {
      border-radius: 10px;
   }
   area {
      border:1px solid black;
   }
</style>
</head>
<body>
<form>
<fieldset>
<legend>Links-Collection-length</legend>
<a href="https://www.google.com">Google</a>
<a href="https://www.bing.com">Bing</a>
<input type="button" value="Get Links" onclick="getLinks()">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
   var divDisplay = document.getElementById("divDisplay");
   var extStyle = document.getElementById("extStyle");
   function getLinks(){
      var links = document.links.length;
      divDisplay.textContent = 'Total Links: '+links;
      for (var i = 0; i < links; i++) {
         divDisplay.textContent += '--> '+document.links[i]+' ';
      }
   }
</script>
</body>
</html>

Output

This will produce the following output −

Before clicking ‘Get Links’ button −

After clicking ‘Get Links’ button −

Updated on: 30-Jul-2019

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements