Coding with Jesse

Using the a tag without attributes

Did you know you can use <a> by itself without href, name, id or any other attributes?

The W3C says this in the HTML 4 specs:

Authors may also create an A element that specifies no anchors, i.e., that doesn't specify href, name, or id. Values for these attributes may be set at a later time through scripts.

Weird, eh? How often do the HTML specs talk about putting elements in for scripting purposes? I had assumed never.

So why would you want to use an empty <a>? I don't think it's so practical for scripting purposes, because it'd be better to dynamically add a link using scripting. But it does make sense from a styling point of view.

If you are using a list of links for a navigation or tabs or something, you probably don't want the active link/tab to be clickable. This can confuse users, because they may think that this link/tab goes somewhere else, when really it just points at the current page.

Normally to approach this, I would just remove the <a> from the <li>. But my CSS relied on there being a link there in order to set a background on it. So instead I just removed the href and used an 'active' class like this:

<ul class="nav">
   <li><a href="/">Home</a></li>
   <li class="active"><a>Page 1</a></li>
   <li><a href="/page2">Page 2</a></li>
</ul>

<style type="text/css">
.nav li {
   list-style: none;
   float: left;

   /* put a repeated background image on the list item */
   background-image: url(nav_background.gif);
}
.nav li a {
   display: block;
   height: 25px;
   padding: 0 15px;

   /* put a separator image on the right of each link */
   background: url(nav_separator.gif) top right no-repeat;
}
.nav li.active {
   background-image: url(nav_background_active.gif);
}
</style>

Now the separator image nav_separator.gif is still used on the empty <a>.

Most browsers will render the link differently, like removing the underline and colouring it different. They seem to treat it as if it's just a <span>.

You might argue that this uses unnecessary markup for purely display purposes. I'd argue that it's better to have a link that can't go anywhere than a link with an href that still goes nowhere.

There are probably other ways to take advantage of this. I'd love to hear any other ways that you think this might be useful.

Published on December 21st, 2006. © Jesse Skinner

About the author

Jesse Skinner

I'm Jesse Skinner. I'm a self-employed web developer. I love writing code, and writing about writing code. Sometimes I make videos too. Feel free to email me if you have any questions or comments, or just want to share your story or something you're excited about.