Should I make HTML Anchors with 'name' or 'id'?
Asked Answered
F

15

849

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?

Fascism answered 27/1, 2009 at 18:57 Comment(4)
The link should actually be http://example.com#foo (so without the / before #)Tramway
Actually, http://example.com#foo and http://example.com/#foo are equivalent as defined in one of the RFCs on URIs.Evangel
Please, check this answer: https://mcmap.net/q/47838/-best-practice-access-form-elements-by-html-id-or-name-attributeCambist
Note that <h1 id="foo"></h1> can be referenced from window.foo in Javascript, which may not be what you are expecting, see https://mcmap.net/q/46718/-should-i-make-html-anchors-with-39-name-39-or-39-id-39Tarpan
C
668

According to the HTML 5 specification, 5.9.8 Navigating to a fragment identifier:

For HTML documents (and the text/html MIME type), the following processing model must be followed to determine what the indicated part of the document is.

  1. Parse the URL, and let fragid be the <fragment> component of the URL.
  2. If fragid is the empty string, then the indicated part of the document is the top of the document.
  3. If there is an element in the DOM that has an ID exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  4. If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  5. Otherwise, there is no indicated part of the document.

So, it will look for id="foo", and then will follow to name="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.

Cere answered 27/1, 2009 at 19:10 Comment(10)
There’s no implied relationship between that algorithm and validity. The <a name> is invalid in HTML5 as currently drafted.Nafis
Actually it does not apply to other "named elements". As far as the name attributes goes it just applies to <a name>. However, that attribute may not be used by authors. It just has to be honored by user agents for older HTML pages.Irradiant
Does anyone know what is the current browser support for this spec, since it's still only a draft?Tahsildar
@RafaelSoares <h1 id="foo">Foo Title</h1> works even in IE6 and is part of HTML 4.01 specificationTaliped
It won't look for name="foo" but for <a name="foo">. See linkIrma
@ColeJohnson It's still invalid.Damoiselle
In an HTML5 document with a name="foo" and a id="foo" (independently of their order within the page), Chrome and Firefox will jump to the id, but IE (tested in 11) and Edge will jump to the nameEffective
The edit mentions "other named elements", but the algorithm itself only mentions "an a element". I don't get it, what are those other named elements ?Lindahl
The name shouldn't work for svg reference (example: use name instead id in w3schools.com/graphics/tryit.asp?filename=trysvg_linear)Rakia
current deeplink into the living HTML spec: html.spec.whatwg.org/multipage/…Cate
N
197

You shouldn’t use <h1><a name="foo"/>Foo Title</h1> in any flavor of HTML served as text/html, because the XML empty element syntax isn’t supported in text/html. However, <h1><a name="foo">Foo Title</a></h1> is OK in HTML4. It is not valid in HTML5 as currently drafted.

<h1 id="foo">Foo Title</h1> is OK in both HTML4 and HTML5. This won’t work in Netscape 4, but you’ll probably use a dozen other features that don’t work in Netscape 4.

Nafis answered 27/1, 2009 at 19:37 Comment(6)
+1 for talking about browser support. Is NS4 the only one not supporting url#id => element.id?Pernicious
@Pernicious Couldn't find an answer, so I did some testing. I found that even very old browsers treat ids just like name anchors in terms of URL fragments and compatibility of the CSS :target selector. Tested: Chrome 6, Firefox 1.5, IE6, Opera 8.02, Safari 3.1.2, Netscape 7.2, Lynx 2.24, and mobile browsers: Android 2.2, Chrome 26, Dolphin 9.3, Firefox 19, IE10, Safari 4, and Opera Mini 5.1.Joycejoycelin
@smhmic, I found one. The Off-By-One web browser recognizes anchors defined via <a name="foo"/> but won't recognize anchors defined via <sometag id="foo"> OB1 was last updated >8 years ago. Its author boasts that it "may be the world's smallest and fastest web browser with full HTML 3.2 support." It claims support for Win95 thru XP, but it works fine w/ 64-bit Win7. So, why have such a dinosaur? For testing, of course, to make sure my sites don't break too badly w/ truly antique browsers. Also, I also carry OB1 on a flash drive. It is tiny, self-contained & immune from infections.Syngamy
Reading this in 2016 be like.. Netscape 4?Posterity
Im using Outlook the enterprise email app i guess and when I put <a id="something">scroll to element</a> it doesnt work, but using name instead of id works which is sad.Flagler
using `<a name="something" id="something></a>[ELEMENT TO SCROLL TO] is probably best because it's compatible, & it doesn't style whatever's in the element to scroll to.Tonsil
C
57

I have to say if you are going to be linking to that area in the page... such as page.html#foo and Foo Title isn't a link you should be using:

<h1 id="foo">Foo Title</h1>

If you instead put an <a> reference around it your headline will be influenced by an <a> specific CSS within your site. It's just extra markup, and you shouldn't need it. I'd highly recommend placing an id on the headline, not only is it better formed, but it will allow you to either address that object in Javascript or CSS.

Chloromycetin answered 27/1, 2009 at 19:3 Comment(2)
Not only that but I have been fighting a strange error where display: none stuff was showing up in IE. Lacking any idea of a point of attack I threw it at a validator which flagged the <a name="foo"> entries so I changed them--and now the display: none is working fine.Faison
This is more than enough, no anchor tag needed for the sake of the effect.Simonize
R
30

Wikipedia makes heavy use of this feature like this:

<a href="#History">[...]</a>
<span class="mw-headline" id="History">History</span>

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:

  • "Names and ids are in the same namespace..." - Two attributes with the same namespace is just crazy. Let's just say deprecated already.
  • "Anchors elements without href atribute" - Yet again, the nature of an element (hyperlink or not) is defined by having an atribute?! Double crazy. Common sense says to avoid it altogether.
  • If you ever style an anchor without a pseudo-class, the styling applies to each. In CSS3 you can get around this with attribute selectors (or same styling for each pseudoclass), but still it's a workaround. This usually doesn't come up because you choose colors per pseudo-class, and the underline being present by default it only makes sense to remove, which makes it the same as other text. But you ever decide to make your links bold, it'll cause trouble.
  • Netscape 4 might not support the id feature, but still an unknown attribute won't cause any trouble. That's what called compatibility for me.
Remuneration answered 25/3, 2013 at 14:46 Comment(7)
Suggest edit bullet 3 of 4: If you ever style a {color:red} it will color both your <a href> links AND your <a name> fragments. You can get around this with pseudo classes a:link {color:red]} or attribute selectors a:not([href]) {color:red;}Payson
You're right, but for me bullet 3 says exactly this. Might be my english though...Erminna
Finally, I've got your point: "If you ever style an anchor without a pseudo-class, the styling applies to each." Ambiguous: You might think "each pseudoclass". Right. But I was thinking of "each case" of using an anchor, which means named and href-ed. Clarified. :) No need to edit after your comment, but I can if you insist. But also it still not prone to happen with colors, as you usually intend keep them different, but still same case with font-weight...Erminna
enjoyed reading your comments @ZoltánMorvai. "double crazy" and "netscape 4" doubleplusgood.Southdown
Two attributes with the same namespace is crazy - not really. When doing user-generated content, it is very useful to be able to specify something as a fragment link <a name="heading1"></a> ... document.html#heading1 without setting the ID, because the ID may clash with another ID on the page. It's a shame they didn't put the name attribute in HTML5.Francoise
@Francoise I can't believe no one else has mentioned this. Is there any safe alternative to <a name="...">?Mercuric
Not that I'm aware of.Francoise
D
15
<h1 id="foo">Foo Title</h1>

is what should be used. Don't use an anchor unless you want a link.

Dm answered 25/6, 2009 at 19:49 Comment(1)
Identical to Tim Knight's answer, posted half a year before this one. -1Regalia
B
15

Heads up for JavaScript users: all IDs become global variables under window.

<h1 id="foo">Foo Title</h1>

Just created the JS global:

window.foo

The value of window.foo will be the HTMLElement for the h1.

Unless you can guarantee all values used in id attributes are safe, you may prefer sticking to name:

<h1 name="foo">Foo Title</h1>
Bodkin answered 17/2, 2015 at 18:23 Comment(4)
The good news is that you can't overwrite the functions defined in window. For example, <div id="open"></div> won't overwrite the function window.open.Tarpan
Why should you guarantee that all values used in id attributes are safe?Ursula
Article about this gotcha: css-tricks.com/…Tarpan
Thanks @Tarpan - that's a good reference, I've included it as a link in the answer.Bodkin
E
9

ID method will not work on older browsers, anchor name method will be deprecated in newer HTML versions... I'd go with id.

Exclusive answered 27/1, 2009 at 19:2 Comment(6)
Do you have a source for those claims? Don't get me wrong; I'm just generally interested.Fascism
That sheds no light on “will not work on older browsers”. – Which browsers are these, apart from Netscape 4??Erepsin
I've tried using the id on a div, and it works even in IE 7. Couldn't test in IE 6 though.. but who uses IE 6 nowadays...Mandorla
@deathApril in certain cases (depends on HASLAYOUT) it's buggy.Coldblooded
@RobertSiemer Works nearly universally -- see my comment under this answer.Joycejoycelin
@Coldblooded Seemed to work both with and without hasLayout on IE6 on WinXP SP2.Joycejoycelin
Y
9

There's no semantic difference; the trend in the standards is toward the use of id rather than name. However, there are differences that may lead one to prefer name in some cases. The HTML 4.01 specification offers the following hints:

Use id or name? Authors should consider the following issues when deciding whether to use id or name for an anchor name:

  • The id attribute can act as more than just an anchor name (e.g., style sheet selector, processing identifier, etc.).
  • Some older user agents don't support anchors created with the id attribute.
  • The name attribute allows richer anchor names (with entities).
Yesteryear answered 27/1, 2009 at 19:26 Comment(6)
To be clear, when they say "older user agents" they mean REALLY old user agents. I wouldn't worry about that.Sammiesammons
HTML5 allows “rich” IDs as well. Does anyone have version numbers of browsers with a market share larger than 0.1% that can’t handle id-anchored fragments? – Or is the dinosaur Netscape 4.7 actually the most spread one?Erepsin
FWIW, I couldn't get id anchors to work in Safari for iOS 5, so it's not just browsers that were already "really old" in '09. I had to add names to get my site to work properly on the iPad. This might have been fixed by now, I don't own any iOS 6 devices to check.Felsite
@DanielSaner really? so en.wikipedia.org/wiki/IPad#Applications doesn't work on your iPad?Taliped
I just checked again; it doesn't work with Safari on my iPad 2 with iOS 5. Your link always lands me at the top of the article. It does work with Opera though. I also tried it on my phone: id anchors don't work on the standard browser that comes with Gingerbread 2.3.7, but do in recent versions of Opera and Firefox.Felsite
@DanielSaner I used simulators to test Mobile Safari 5.02 & 5.1, and Android Browser 2.2 & 2.3, and the id anchors seem to work universally. If this simple example doesn't work on your mobile, I would check the device accessibility settings. (@deathApril Wikipedia mobile site has Javascript that effectively causes the URL fragment to be ignored.)Joycejoycelin
T
6

In html 5, the id="" attribute defines a unique identifier for an element, which is also an anchor for a fragment link. In previous html standards, the name="" attribute of the <a> element defines an anchor for a fragment link. I recommend something like:
<a name="foo" id="foo"></a><h1>Foo Title</h1>
Because support for the id="" attribute is a bit spotty(even though the latest releases of all major browsers support it, the releases that don't aren't more than a few years old[And it's best not to break something if there isn't a good reason to]). It's compatible, & it doesn't style whatever's in the link'd element, for the closing </a> is still outside the element, but it's still valid in all current standards.

Be sure that the name="" and id="" attributes of the <a> element are the same.

Tonsil answered 25/6, 2017 at 17:45 Comment(1)
Not everything that uses HTML is a browser. I'm using a Java library that displays information in a window using HTML. This is the only method that worked. It's the name attribute on an anchor tag that was required; placing attributes on an hN or span didn't work.Newsstand
V
3

I have a web page consisting of a number of vertically stacked div containers, identical in format and differing only in serial number. I wanted to hide the name anchor at the top of each div, so the most economical solution turned out to be including the anchor as an id within the opening div tag, i.e,

<div id="[serial number]" class="topic_wrapper">
Ventriloquy answered 13/6, 2012 at 2:10 Comment(0)
C
2

The second sample assigns a unique ID to the element in question. This element can then be manipulated or accessed using DHTML.

The first one, on the other hand, sets a named location within the document, akin to a bookmark. Attached to an "anchor", it makes perfect sense.

Contracture answered 27/1, 2009 at 19:4 Comment(0)
I
2

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.

Insobriety answered 31/12, 2011 at 4:23 Comment(1)
That's a good point. More info on wbr: w3.org/TR/html-markup/wbr.html Use <wbr id="foo" /> rather than <a name="foo"></a>Raffin
P
1

How about using name attribute for old browsers and id attribute to the new browsers. Both options will be used and fallback method will be implemented by default!!!

Pyridine answered 20/6, 2013 at 7:36 Comment(0)
P
1

It's not about support right now, because who would care in 2021 about older browsers than IE6?

Notice that Stackoverflow is still using anchor and 'name' attribute instead of 'name' attribute.

Why?

Because you:

  1. can't have two values for id on SINGLE element.

#sample
{
  color: red; 
}
<div id="postNr4245 sample"> Sample text </div>  <!-- coloring doesn't work -->

<a href="#postNr4245">Jump to Post</a> <!-- jumping doesn't work -->

Ok, you can say you can use 'class' for the sake of things like that.

It's true but if there is only single element that needs to be styled on your site then you shouldn't use class.

Why?

Because if you use CSS selector #idName and web browser finds that element it won't look further. It speeds loading of your website.

If you use .class it needs to look for every place of your DOM because web browser doesn't know if you had used .class once or more times.

  1. You can't start 'id' value with number if you want to style it in CSS or use JS to parse it. You can however start 'name' value with number.
Pricket answered 24/6, 2021 at 9:54 Comment(0)
F
-3

The whole "named anchor" concept uses the name attribute, by definition. You should just stick to using the name, but the ID attribute might be handy for some javascript situations.

As in the comments, you could always use both to hedge your bets.

Franklin answered 27/1, 2009 at 18:59 Comment(4)
When using both, are the id:s and names globally unique? as in, can I use the same string as both the id and the name?Fascism
You can, but some people think it's bad practice.Franklin
According to the HTML specification, if both are present, name and id should be identical. It also says that names and ids are in the same namespace. The HTML validator service doesn't check for these, and I doubt browsers care, but they seem like good guidelines to follow anyway.Yesteryear
Reality redefined! <a name... was ill from the beginning, and CSS link styling makes it even sicker.Erepsin

© 2022 - 2024 — McMap. All rights reserved.