On Links and IDs

After writing Best. Comment. Ever., I realized comment permalinks were not working on my blog. Clicking the link brought up the page, but failed to scroll to the comment.

Jörg offers this advice:

Firefox does right, and so does safari: You anchors name (”…#comment-7155″) contains a “-”, which is an invalid name. Try something like “#comment7155″, it will work.

While his suggestion served as a catalyst for me to finally investigate the problem, I was not convinced “-” was the cause. So I researched the HTML specification, which has this to say:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (”-”), underscores (”_”), colons (”:”), and periods (”.”)

Dashes are frequently used in URLs, so this cannot be the problem.

The Solution

While my heavily customized WordPress theme defined links, it failed to define anchors or IDs. So the links were going nowhere. I had to edit comments.php and add this ID to a <div> tag:

<div id="comment-<?php comment_ID() ?>" class="comment">

And that fixed the problem. I also re-learned some things about HTML that I probably knew at one point, but forgot:

  • On the receiving end of an anchor-type link, you omit the # character
  • You don’t have to link to <a name=”something”>. As my theme shows, you can link to <div id=”something”>

I suspect WordPress works fine out of the box, but I must have screwed it up when creating this theme.


Tony Lara Says:

I have the same problem, but it appears only to be with firefox. I didn’t know you could link with the id of the elements, good to know.