When one wants to refer to some part of a webpage with the \"http://example.com/#foo
\" method, should one use
F
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!!!
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.
<h1 id="foo">Foo Title</h1>
is what should be used. Don't use an anchor unless you want a link.
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.
- Parse the URL, and let fragid be the <fragment> component of the URL.
- If fragid is the empty string, then the indicated part of the document is the top of the document.
- 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.
- 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.
- 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.
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>
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.