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);
Quoting from MDN
The links property returns a collection of all
<area>
elements and<a>
elements in a document with a value for thehref
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With