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 that 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
<!DOCTYPE html> < html lang = "en" > < head > < title > Display the number of links present in a document using JavaScript </ title > </ head > < body > < h1 style = "color: green;" > neveropen </ h1 > < h3 > Display the number of links present in document </ h3 > < a href = "www.geeksforgeeks.org" > neveropen Home Page </ a > < a href = "practice.geeksforgeeks.org" > neveropen Practice </ a > < script > console.log("Number of links: " + document.links.length); </ script > </ body > </ html > |
Output:
Example 2: In this example, we will print the number of links on the document.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < title > Display the number of links present in a document using JavaScript </ title > </ head > < body > < h1 style = "color: green;" > neveropen </ h1 > < h3 > Display the number of links present in document </ h3 > < p > < a href = "www.geeksforgeeks.org" > neveropen Home Page </ a > </ p > < p > < a href = "practice.geeksforgeeks.org" > neveropen Practice </ a > </ p > < button onclick = "fun()" > Click Here to Get Number of Links </ button > < p id = "gfg" ></ p > < script > function fun() { document.getElementById('gfg') .innerHTML = "Number of links: " + document.links.length; } </ script > </ body > </ html > |
Output: