When creating the id
attributes for HTML elements, what rules are there for the value?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a way to play audio on a mobile browser w
- HTML form is not sending $_POST values
- implementing html5 drag and drop photos with knock
-
Why does the box-shadow property not apply to a
Since ES2015 we can as well use -almost- all unicode characters for ID's, if the document charset is set to UTF8.
Test out here: https://mothereff.in/js-variables
Read about: https://mathiasbynens.be/notes/javascript-identifiers-es6
for
HTML5
At least one character, no spaces.
This opens the door for valid use cases such as using accented characters. It also gives us plenty of more ammo to shoot ourselves in the foot with, since you can now use id values that will cause problems with both CSS and JavaScript unless you’re really careful.
From the HTML 4 spec...
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 (".").
EDIT: d'oh! Beaten to the button, again!
In practice many sites use
id
attributes starting with numbers, even though this is technically not valid HTML.The HTML 5 draft specification loosens up the rules for the
id
andname
attributes: they are now just opaque strings which cannot contain spaces.# : . * !
symbols<base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>.
You can technically use colons and periods in id/name attributes, but I would strongly suggest avoiding both.
In CSS (and several JavaScript libraries like jQuery), both the period and the colon have special meaning and you will run into problems if you're not careful. Periods are class selectors and colons are pseudo-selectors (eg., ":hover" for an element when the mouse is over it).
If you give an element the id "my.cool:thing", your CSS selector will look like this:
Which is really saying, "the element with an id of 'my', a class of 'cool' and the 'thing' pseudo-selector" in CSS-speak.
Stick to A-Z of any case, numbers, underscores and hyphens. And as said above, make sure your ids are unique.
That should be your first concern.