Curtis
Curtis

Reputation: 103358

Should I specify anchors with an anchor element?

In the past I've seen examples of anchors being specified using anchor elements, and id or name attributes (with id taking precedence).

However, is there any particular reason why I should use an anchor element over any other element, in terms of accessibility/cross-browser support?

For example I could a URL http://domain.com/page.htm#faq with the following markup:

<a id="faq"></a>
<h1>Frequently Asked Questions</h1>

Which could be simplified to:

<h1 id="faq">Frequently Asked Questions</h1>

Is there any harm in using this second markup? Is there a particular reason why developers would prefer empty anchors over attaching the id to a more relevant element?

Upvotes: 0

Views: 61

Answers (2)

Vladislav Qulin
Vladislav Qulin

Reputation: 1942

It's ok to write your code. There are two points of using first code:

  1. Historical reasons.

  2. HtmlHelpers in any html-drive, like Razor. For example, it looks fine for me to use something like this:

    public static MvcHtmlString Anchor<TModel>(this HtmlHelper<TModel> htmlHelper, string anchorId)
    {
        var tag = new TagBuilder("a");
        tag.Attributes.Add("id", anchorId);
        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }
    

In my MVC project.

Upvotes: 0

Oded
Oded

Reputation: 499002

is there any particular reason why I should use an anchor element over any other element, in terms of accessibility/cross-browser support?

No, not any more.

Historically (pre HTML 4), named anchors were the only way to have in page anchors.

Is there any harm in using this second markup?

That's the recommended way - that's how you should do it.

Is there a particular reason why developers would prefer empty anchors over attaching the id to a more relevant element?

Only lack of learning and adapting to change ;)

Upvotes: 3

Related Questions