Francisc
Francisc

Reputation: 80505

Is there any problem with using a number as an id or class for an HTML4, XHTML or HTML5 document?

As the title suggests, I am "afraid" to have elements with either id="12" or class="12". I know the spec allows this, especially for HTML5, but are there any problems you encountered using this?

In this particular case I have <li> elements that contain months and I want to give them a class name with the month number (e.g. 1 for January) to reference them in JavaScript. And instead of class="1" I do class="mon-1".

Thanks.

Upvotes: 0

Views: 75

Answers (2)

Juri
Juri

Reputation: 32930

What about using the data-xxxxx attributes on DOM elements? Handy if you use jQuery:
http://api.jquery.com/data/

Basically you have

<div id="someElement" data-id="5">
  ...
</div>

and you can then read it from your JavaScript code with

var theId = $("#someElement").data("id");

Here's an example to try it out: http://jsbin.com/ulujek/2/edit

HTML5 only, though..

Upvotes: 2

Semyazas
Semyazas

Reputation: 2101

If you're using HTML4 or XHTML and want your documents to be valid, you cannot use a digit for the id. It will however probably work perfectly fine in most mainstream browsers, since they tend to not break your layout just because of a wrongly named id.

Problems more often occur due to : or . being inside an id name and trying to select those in JavaScript.

I would still advise against using only digits for the id, if you're not using HTML5. Just because it adheres to standards. If you're using mon-1 as the id, that wouldn't be a problem either, it is allowed to contain digits, just not start with one.

If you want to use a class name of: .mon-1 that is perfectly fine anyways, because classes naming-restriction is to not contain a space.

Upvotes: 2

Related Questions