Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why link numbers are different?

Tags:

javascript

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);
like image 323
Tony Avatar asked Mar 11 '23 13:03

Tony


1 Answers

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

like image 159
Tushar Avatar answered Mar 19 '23 02:03

Tushar