user2587454
user2587454

Reputation: 913

HTML anchor link as name and not id

is it possible to add skip to content to link to name and not for id?

<a id="skiptocontent" href="#main" class="">skip to main content</a>
<h1 name="main">Main</h1>

Upvotes: 1

Views: 4938

Answers (1)

trincot
trincot

Reputation: 349908

No, this is not possible. There are some work-arounds:

1. Add id property

Obviously, you could add the id property to the target element:

<h1 name="main" id="main">Main</h1>

2. Add an anchor

If the target needs to be identified by name, add an anchor:

<a name="main"/><h1>Main</h1>

But in HTML5 the name attribute for the a element is obsolete.

3. Use scripting to add the id attribute

You could add a script that will add the missing id attribute on page load:

<script>
    // find first element that has the name attribute set to "main":
    var element = document.querySelector('[name=main]');
    // copy that value into the id attribute
    element.setAttribute('id', element.getAttribute('name')); 
</script>

You should then put this script block at the end of the document, so just before the closing </body> tag.

4. Add script to the source link:

You could replace the href value with a script that will do the action based on the name attribute:

<a id="skiptocontent" 
   href="javascript:document.querySelector('[name=main]').scrollIntoView();" 
   class="">skip to main content</a>

Remark

As you tagged the question with HTML5, it should be noted that in HTML5 there is a clear moving away from using the name attribute as a target. id attributes are preferred in HTML5. That makes sense, because name values do not have to be unique, while id values have to be.

Upvotes: 6

Related Questions