Why can an element id not start with an integer?
This question already has an answer here:
Why can an element id not start with an integer?
They can. But a CSS ID selector cannot start with a digit. Eg, this HTML is valid:
<div id="1foo">testing 1 2 3</div>
...but this CSS is not valid:
#1foo {
color: green;
}
The CSS standard says that an id
selector cannot start with a digit:
An ID selector contains a "number sign" (U+0023, #) immediately followed by the ID value, which must be an CSS identifiers.
And then defining CSS identifier:
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9]
and ISO 10646 characters U+00A0
and higher, plus the hyphen ( -
) and the underscore ( _
); they cannot start with a digit , two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?"
may be written as "B&W?"
or "B26 W3F"
.
(My emphasis.)
So in theory, you can work around the #1foo
not working by escaping the digit in the CSS selector. For instance:
HTML:
<div id="1foo">testing 1 2 3</div>
CSS:
#31 foo {
color: green;
}
...where 31
is the character code for "1"
in hex. Live Example:
#31 foo {
color: green;
}
<div id="1foo">testing 1 2 3</div>
Actually, you can make an id start with a number, and methods like document.getElementById
works just fine with that.
But some older page use the legacy IE standard that an element like
<div id="hello">World</div>
can be referenced as document.hello
. Of course this syntax doesn't work, but I think document["123id"]
can fix it.
But, above all, CSS selectors don't work well with id's starting with a number. You have to escape them:
#123id {color: red;} /* It doesn't work */
#31 23id {color: blue;} /* Oh yeah! */
Worth the effort? Probably not.
From the HTML 4 specification:
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.djcxy.com/p/15444.html上一篇: jQuery语法错误,无法识别的表达式
下一篇: 为什么元素ID不能以整数开头?