Tony Tony - 11 days ago 5
Javascript Question

Why link numbers are different?

I tried to count links within a page using JS, but got different results. Why there is a difference?



var intLNK = document.links.length;
console.log(intLNK);

var intA = document.getElementsByTagName("a").length;
console.log(intA);




Answer

Quoting from MDN

The links property returns a collection of all <area> elements and <a> elements in a document with a value for the href attribute.

document.getElementsByTagName("a").length;

will return the anchor elements irrespective of href attribute. You may use

document.querySelectorAll('a[href]').length

to get the number of anchors having href attribute.

If you're interested in performance of two see https://jsperf.com/document-links-vs-document-queryselectorall-aThanks to Robert Weber