开发者

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

开发者 https://www.devze.com 2023-03-23 11:30 出处:网络
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?

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.


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.


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..

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号