2

I tried document.links and document.anchors in the dev console on a page, and there were 162 links but 255 anchors. However, they are all <a> elements.

Up until now, I thought that links and anchors were exact synonyms (as long as they both referred to <a> tags). What is the difference technically and or semantically?

j08691
  • 204,283
  • 31
  • 260
  • 272
labyrinth
  • 13,397
  • 7
  • 35
  • 44

2 Answers2

5

document.anchors quite simply returns a collection of all anchors in a document that have a value for the name attribute. It has been removed from web standards and should no longer be used.

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

So they're similar, but definitely not identical. document.anchors would find anchors like <a name="foo">foo</a> (while document.links wouldn't), and document.links would find <a href="foo.html">foo</a> and <area shape="circle" coords="75,75,75" href="foo.html"> (whiledocument.anchors wouldn't).

j08691
  • 204,283
  • 31
  • 260
  • 272
1

An anchor is a a element with a name attribute. In the old days, they were used as linkable section identifiers that can be targeted by the URI fragment identifier. Today, we use id attributes for those.

A link is an a (or area) element with a href attribute. It links another page or an anchor thereon.

document.links and document.anchors are live HTML collections of the respective elements in that document. They're rarely used today, getElementById and querySelectorAll (or the various selector libraries) offer better choices. anchors is even deprecated similar to the horrible document.all.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375