Why are link numbers different?

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

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

var intA = document.getElementsByTagName("a").length;
console.log(intA);
Run codeHide result
+4
source share
5 answers

Quote from MDN

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

document.getElementsByTagName("a").length;

will return anchor elements regardless of attribute href. you can use

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

to get the number of anchors that have an attribute href.

If you are interested in the performance of the two, see https://jsperf.com/document-links-vs-document-queryselectorall-a Thanks Robert Weber

+3
source

document.links a ( <area>), href, - .

(mdn)

+2

a href

+1

, HTML.

1) .  <A Name = "Section1"> ... </A>

2) .  < A HREF = "target location"> ... </A>

document.links.length HREF, document.getElementsByTagName("a").length A .

.

+1

, href, . .

href , jquery,

$('a[href]').length
0

Source: https://habr.com/ru/post/1662227/


All Articles