Skip to content

March 28, 2010

IDs starting with Numbers

We all know the ID and NAME conventions on HTML tags. The ID must start with a letter, and then afterwards can be any number, letter, hyphen, underscore or colon. So creating an ID of 56green would not work, as it begins with the number 5. Where as S6green would be perfectly valid.

Recently I wrote a greasemonkey script, and I found (to my horror) the website had used alphanumeric strings as their IDs. That was fine, but the catch was they didn’t check to see if each string followed the standards, meaning half started with a number.

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 (“.”).

http://www.w3.org/TR/html4/types.html

It didn’t bother them, as the elements were not directly referred to. However it was a pain for me and my script, and so I had to find a way to call the element.

In my example, the name of the element will be 25tuna.

$('#25tuna').hide();
// In this case, nothing would happen. The element would not hide,
// even if it was still on the page.

$('#25tuna').length
// Would = 0, even though we can see the element sitting on the page.

Instead, I ended up having to use a workaround for the issue.

$('div[id="25tuna"]').length; // now will equal 1
$('div[id="25tuna"]').hide(); // should now work

So while you can’t refer to the element using the regular notation, you can use it through attribute notation (since ID is another attribute on an HTML element).

This is not ideal, and does introduce its own performance issues. If it’s a case where you are able to alter the HTML element on the page directly (being your own website), do that and make the ID/NAME attributes conform. It will save effort and frustration.

However if you are writing a greasemonkey script (in jQuery like I did) then you may find this is your only option.

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

blog comments powered by Disqus