Display the number of links present in a document using JavaScript
Any webpage that is loaded in the browser can be represented by the Document interface. This serves as an entry point to the DOM tree and the DOM tree contains all elements such as <body> , <title>, <table> ,<a> etc. We can create a Document object using the Document() constructor.
There are many properties of these Document objects. One such property is links. The links property gives us a collection of all <area> elements and <a> elements in a document. One more property is the length property. The length property tells us the number of links present in the document.links array.
So, the document.links.length statement gives us the number of links present in a document. Below HTML document contains a JavaScript piece of code which tells the number of links present in the document:
Example 1: In this example, we will print the count of links on the console
HTML
< a href = "www.geeksforgeeks.org" ></ a > < a href = "practice.geeksforgeeks.org" ></ a > < script > console.log("Number of links: " + document.links.length); </ script > |
Output:
2
Example 2: In this example, we will print the number of links on the document.
HTML
< button onclick = "fun()" > Click here to check number of links </ button > < p id = "gfg" ></ p > < a href = "www.geeksforgeeks.org" ></ a > < a href = "practice.geeksforgeeks.org" ></ a > < script > function fun(){ document.getElementById('gfg') .innerHTML = "Number of links: " + document.links.length; } </ script > |
Output:

Please Login to comment...