When one wants to refer to some part of a webpage with the "http://example.com/#foo
" method, should one use
<h1><a name="foo"/>Foo Title</h1>
or
<h1 id="foo">Foo Title</h1>
They both work, but are they equal, or do they have semantic differences?
Heads up for JavaScript users: all IDs become global variables under window.
Just created the JS global:
The value of
window.foo
will be theHTMLElement
for theh1
.Unless you can guarantee all values used in
id
attributes are safe, you may prefer sticking toname
:Just an observation about the markup The markup form in prior versions of HTML provided an anchor point. The markup forms in HTML5 using the id attribute, while mostly equivalent, require an element to identify, almost all of which are normally expected to contain content.
An empty span or div could be used, for instance, but this usage looks and smells degenerate.
One thought is to use the wbr element for this purpose. The wbr has an empty content model and simply declares that a line break is possible; this is still a slightly gratuitous use of a markup tag, but much less so than gratuitous document divisions or empty text spans.
According to the HTML 5 specification, 5.9.8 Navigating to a fragment identifier:
So, it will look for
id="foo"
, and then will follow toname="foo"
Edit: As pointed out by @hsivonen, in HTML5 the
a
element has no name attribute. However, the above rules still apply to other named elements.There's no semantic difference; the trend in the standards is toward the use of
id
rather thanname
. However, there are differences that may lead one to prefername
in some cases. The HTML 4.01 specification offers the following hints:Use
id
orname
? Authors should consider the following issues when deciding whether to useid
orname
for an anchor name:Wikipedia makes heavy use of this feature like this:
And Wikipedia is working for everybody, so I would feel safe sticking with this form.
Also don't forget, you can use this not only with spans but with divs or even table cells, and then you have access to the :target pseudo-class on the element. Just watch out not to change the width, like with bold text, cause that moves content around, which is disturbing.
Named anchors - my vote is to avoid:
is what should be used. Don't use an anchor unless you want a link.