Related
When creating the id attributes for HTML elements, what rules are there for the value?
For HTML 4, the answer is technically:
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 (".").
HTML 5 is even more permissive, saying only that an id must contain at least one character and may not contain any space characters.
The id attribute is case sensitive in XHTML.
As a purely practical matter, you may want to avoid certain characters. Periods, colons and '#' have special meaning in CSS selectors, so you will have to escape those characters using a backslash in CSS or a double backslash in a selector string passed to jQuery. Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids.
For example, the HTML declaration <div id="first.name"></div> is valid. You can select that element in CSS as #first\.name and in jQuery like so: $('#first\\.name'). But if you forget the backslash, $('#first.name'), you will have a perfectly valid selector looking for an element with id first and also having class name. This is a bug that is easy to overlook. You might be happier in the long run choosing the id first-name (a hyphen rather than a period), instead.
You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder "was it firstName or FirstName?" because you will always know that you should type first_name. Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don't mix them.
A now very obscure problem was that at least one browser, Netscape 6, incorrectly treated id attribute values as case-sensitive. That meant that if you had typed id="firstName" in your HTML (lower-case 'f') and #FirstName { color: red } in your CSS (upper-case 'F'), that buggy browser would have failed to set the element's color to red. At the time of this edit, April 2015, I hope you aren't being asked to support Netscape 6. Consider this a historical footnote.
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 (".").
A common mistake is to use an ID that starts with a digit.
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:
#my.cool:thing { ... /* some rules */ ... }
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.
HTML5: Permitted Values for ID & Class Attributes
As of HTML5, the only restrictions on the value of an ID are:
must be unique in the document
must not contain any space characters
must contain at least one character
Similar rules apply to classes (except for the uniqueness, of course).
So the value can be all digits, just one digit, just punctuation characters, include special characters, whatever. Just no whitespace. This is very different from HTML4.
In HTML 4, ID values must begin with a letter, which can then be followed only by letters, digits, hyphens, underscores, colons and periods.
In HTML5 these are valid:
<div id="999"> ... </div>
<div id="#%LV-||"> ... </div>
<div id="____V"> ... </div>
<div id="⌘⌥"> ... </div>
<div id="♥"> ... </div>
<div id="{}"> ... </div>
<div id="©"> ... </div>
<div id="♤₩¤☆€~¥"> ... </div>
Just bear in mind that using numbers, punctuation or special characters in the value of an ID may cause trouble in other contexts (e.g., CSS, JavaScript, regex).
For example, the following ID is valid in HTML5:
<div id="9lions"> ... </div>
However, it is invalid in CSS:
From the CSS2.1 spec:
4.1.3 Characters and case
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.
In most cases you may be able to escape characters in contexts where they have restrictions or special meaning.
W3C References
HTML5
3.2.5.1 The id
attribute
The id attribute specifies its element's unique identifier (ID).
The value must be unique amongst all the IDs in the element's home
subtree and must contain at least one character. The value must not
contain any space characters.
Note: There are no other restrictions on what form an ID can take; in
particular, IDs can consist of just digits, start with a digit, start
with an underscore, consist of just punctuation, etc.
3.2.5.7 The class
attribute
The attribute, if specified, must have a value that is a set of
space-separated tokens representing the various classes that the
element belongs to.
The classes that an HTML element has assigned to it consists of all
the classes returned when the value of the class attribute is split on
spaces. (Duplicates are ignored.)
There are no additional restrictions on the tokens authors can use in
the class attribute, but authors are encouraged to use values that
describe the nature of the content, rather than values that describe
the desired presentation of the content.
jQuery does handle any valid ID name. You just need to escape metacharacters (i.e., dots, semicolons, square brackets...). It's like saying that JavaScript has a problem with quotes only because you can't write
var name = 'O'Hara';
Selectors in jQuery API (see bottom note)
Strictly it should match
[A-Za-z][-A-Za-z0-9_:.]*
But jQuery seems to have problems with colons, so it might be better to avoid them.
HTML5:
It gets rid of the additional restrictions on the id attribute (see here). The only requirements left (apart from being unique in the document) are:
the value must contain at least one character (can’t be empty)
it can’t contain any space characters.
Pre-HTML5:
ID should match:
[A-Za-z][-A-Za-z0-9_:.]*
Must start with A-Z or a-z characters
May contain - (hyphen), _ (underscore), : (colon) and . (period)
But one should avoid : and . because:
For example, an ID could be labelled "a.b:c" and referenced in the style sheet as #a.b:c, but as well as being the id for the element, it could mean id "a", class "b", pseudo-selector "c". It is best to avoid the confusion and stay away from using . and : altogether.
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 and name attributes: they are now just opaque strings which cannot contain spaces.
Hyphens, underscores, periods, colons, numbers and letters are all valid for use with CSS and jQuery. The following should work, but it must be unique throughout the page and also must start with a letter [A-Za-z].
Working with colons and periods needs a bit more work, but you can do it as the following example shows.
<html>
<head>
<title>Cake</title>
<style type="text/css">
#i\.Really\.Like\.Cake {
color: green;
}
#i\:Really\:Like\:Cake {
color: blue;
}
</style>
</head>
<body>
<div id="i.Really.Like.Cake">Cake</div>
<div id="testResultPeriod"></div>
<div id="i:Really:Like:Cake">Cake</div>
<div id="testResultColon"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var testPeriod = $("#i\\.Really\\.Like\\.Cake");
$("#testResultPeriod").html("found " + testPeriod.length + " result.");
var testColon = $("#i\\:Really\\:Like\\:Cake");
$("#testResultColon").html("found " + testColon.length + " result.");
});
</script>
</body>
</html>
HTML5
Keeping in mind that ID must be unique, i.e., there must not be multiple elements in a document that have the same id value.
The rules about ID content in HTML5 are (apart from being unique):
This attribute's value must not contain white spaces. [...]
Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
This is the W3 spec about ID (from MDN):
Any string, with the following restrictions:
must be at least one character long
must not contain any space characters
Previous versions of HTML placed greater restrictions on the content of ID values (for example, they did not permit ID values to begin with a number).
More information:
W3 - global attributes (id)
MDN attribute (id)
To reference an id with a period in it, you need to use a backslash. I am not sure if it's the same for hyphens or underscores.
For example:
HTML
<div id="maintenance.instrumentNumber">############0218</div>
CSS
#maintenance\.instrumentNumber{word-wrap:break-word;}
From the HTML 4 specification...
The 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 (".").
Also, never forget that an ID is unique. Once used, the ID value may not appear again anywhere in the document.
You may have many ID's, but all must have a unique value.
On the other hand, there is the class-element. Just like ID, it can appear many times, but the value may be used over and over again.
A unique identifier for the element.
There must not be multiple elements in a document that have the same id value.
Any string, with the following restrictions:
must be at least one character long
must not contain any space characters:
U+0020 SPACE
U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+000D CARRIAGE RETURN (CR)
Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
It appears that, although colons (:) and periods (.) are valid in the HTML specification, they are invalid as id selectors in CSS, so they are probably best avoided if you intend to use them for that purpose.
For HTML5:
The value must be unique amongst all the IDs in the element’s home
subtree and must contain at least one character. The value must not
contain any space characters.
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.
IDs are best suited for naming parts of your layout, so you should not give the same name for ID and class
ID allows alphanumeric and special characters
but avoid using the # : . * ! symbols
spaces are not allowed
not started with numbers or a hyphen followed by a digit
case sensitive
using ID selectors is faster than using class selectors
use hyphen "-" (underscore "_" can also be used, but it is not good for SEO) for long CSS class or Id rule names
If a rule has an ID selector as its key selector, don’t add the tag name to the rule. Since IDs are unique, adding a tag name would slow down the matching process needlessly.
In HTML5, the id attribute can be used on any HTML element and In HTML 4.01, the id attribute cannot be used with: <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>.
Any alpha-numeric value,"-", and "_" are valid. But, you should start the id name with any character between A-Z or a-z.
Since ES2015 we can as well use almost all Unicode characters for ID's, if the document character set is set to UTF-8.
Test out here: https://mothereff.in/js-variables
Read about it: Valid JavaScript variable names in ES2015
In ES2015, identifiers must start with $, _, or any symbol with the
Unicode derived core property ID_Start.
The rest of the identifier can contain $, _, U+200C zero width
non-joiner, U+200D zero width joiner, or any symbol with the Unicode
derived core property ID_Continue.
const target = document.querySelector("div").id
console.log("Div id:", target )
document.getElementById(target).style.background = "chartreuse"
div {
border: 5px blue solid;
width: 100%;
height: 200px
}
<div id="H̹̙̦̮͉̩̗̗ͧ̇̏̊̾Eͨ͆͒̆ͮ̃͏̷̮̣̫̤̣Cͯ̂͐͏̨̛͔̦̟͈̻O̜͎͍͙͚̬̝̣̽ͮ͐͗̀ͤ̍̀͢M̴̡̲̭͍͇̼̟̯̦̉̒͠Ḛ̛̙̞̪̗ͥͤͩ̾͑̔͐ͅṮ̴̷̷̗̼͍̿̿̓̽͐H̙̙̔̄͜"></div>
Should you use it? Probably not a good idea!
Read about it: JavaScript: "Syntax error missing } after function body"
No spaces, and it must begin with at least a character from a to z and 0 to 9.
In HTML
ID should start with {A-Z} or {a-z}. You can add digits, periods, hyphens, underscores, and colons.
For example:
<span id="testID2"></span>
<span id="test-ID2"></span>
<span id="test_ID2"></span>
<span id="test:ID2"></span>
<span id="test.ID2"></span>
But even though you can make ID with colons (:) or period (.). It is hard for CSS to use these IDs as a selector. Mainly when you want to use pseudo elements (:before and :after).
Also in JavaScript it is hard to select these ID's.
So you should use first four ID's as the preferred way by many developers around and if it's necessary then you can use the last two also.
Walues can be: [a-z], [A-Z], [0-9], [* _ : -]
It is used for HTML5...
We can add id with any tag.
Help, my Javascript is broken!
Everyone says IDs can't be duplicates.
Best tried in every browser but FireFox
<div id="ONE"></div>
<div id="ONE"></div>
<div id="ONE"></div>
<script>
document.body.append( document.querySelectorAll("#ONE").length , ' DIVs!')
document.body.append( ' in a ', typeof ONE )
console.log( ONE ); // a global var !!
</script>
Explanation
After the turn of the century Microsoft had 90% Browser Market share,
and implemented Browser behaviours that where never standardized:
1. create global variables for every ID
2. create an Array for duplicate IDs
All later Browser vendors copied this behaviour, otherwise their browser wouldn't support older sites.
Somewhere around 2015 Mozilla removed 2. from FireFox and 1. still works.
All other browsers still do 1. and 2.
I use it every day because typing ONE instead of document.querySelector("#ONE") helps me prototype faster; I do not use it in production.
Html ID
The id attribute specifies its element's unique identifier (ID).
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
An element's unique identifier can be used for a variety of purposes, most notably as a way to link to specific parts of a document using fragments, as a way to target an element when scripting, and as a way to style a specific element from CSS.
Uppercase and lowercase alphabets works
'_' and '-' works, too
Numbers works
Colons (,) and period (.) seems to work
Interestingly, emojis work
alphabets → caps & small
digits → 0-9
special characters → ':', '-', '_', '.'
The format should be either starting from '.' or an alphabet, followed by either of the special characters of more alphabets or numbers. The value of the id field must not end at an '_'.
Also, spaces are not allowed, if provided, they are treated as different values, which is not valid in case of the id attributes.
What characters/symbols are allowed within the CSS class selectors?
I know that the following characters are invalid, but what characters are valid?
~ ! # $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #
You can check directly at the CSS grammar.
Basically1, a name must begin with an underscore (_), a hyphen (-), or a letter(a–z), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must2 be a letter or underscore, and the name must be at least 2 characters long.
-?[_a-zA-Z]+[_a-zA-Z0-9-]*
In short, the previous rule translates to the following, extracted from the W3C specification:
In CSS, identifiers (including element names, classes, and IDs in
selectors) can contain only the characters [a-z0-9] and ISO 10646
characters U+00A0 and higher, plus the hyphen (-) and the underscore
(_); they cannot start with a digit, 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 "B\26 W\3F".
Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in -moz-opacity.
1 It's all made a bit more complicated by the inclusion of escaped Unicode characters (that no one really uses).
2 Note that, according to the grammar I linked, a rule starting with two hyphens, e.g., --indent1, is invalid. However, I'm pretty sure I've seen this in practice.
To my surprise most answers here are wrong. It turns out that:
Any character except NUL is allowed in CSS class names in CSS. (If CSS contains NUL (escaped or not), the result is undefined. [CSS-characters])
Mathias Bynens' answer links to explanation and demos showing how to use these names. Written down in CSS code, a class name may need escaping, but that doesn’t change the class name. E.g. an unnecessarily over-escaped representation will look different from other representations of that name, but it still refers to the same class name.
Most other (programming) languages don’t have that concept of escaping variable names (“identifiers”), so all representations of a variable have to look the same. This is not the case in CSS.
Note that in HTML there is no way to include space characters (space, tab, line feed, form feed and carriage return) in a class name attribute, because they already separate classes from each other.
So, if you need to turn a random string into a CSS class name: take care of NUL and space, and escape (accordingly for CSS or HTML). Done.
I’ve answered your question in-depth at CSS character escape sequences. The article also explains how to escape any character in CSS (and JavaScript), and I made a handy tool for this as well. From that page:
If you were to give an element an ID value of ~!#$%^&*()_+-=,./';:"?><[]{}|`#, the selector would look like this:
CSS:
<style>
#\~\!\#\$\%\^\&\*\(\)\_\+-\=\,\.\/\'\;\:\"\?\>\<\[\]\\\{\}\|\`\#
{
background: hotpink;
}
</style>
JavaScript:
<script>
// document.getElementById or similar
document.getElementById('~!#$%^&*()_+-=,./\';:"?><[]\\{}|`#');
// document.querySelector or similar
$('#\\~\\!\\#\\$\\%\\^\\&\\*\\(\\)\\_\\+-\\=\\,\\.\\/\\\'\\;\\:\\"\\?\\>\\<\\[\\]\\\\\\{\\}\\|\\`\\#');
</script>
Read the W3C spec. (this is CSS 2.1; find the appropriate version for your assumption of browsers)
relevant paragraph:
In CSS, identifiers (including
element names, classes, and IDs in
selectors) can contain only the
characters [a-z0-9] and ISO 10646
characters U+00A1 and higher, plus the
hyphen (-) and the underscore (_);
they cannot start with a digit, 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 "B\26 W\3F".
As #mipadi points out in Kenan Banks's answer, there's this caveat, also in the same webpage:
In CSS, identifiers may begin with '-'
(dash) or '_' (underscore). Keywords
and property names beginning with '-'
or '_' are reserved for
vendor-specific extensions. Such
vendor-specific extensions should have
one of the following formats:
'-' + vendor identifier + '-' + meaningful name
'_' + vendor identifier + '-' + meaningful name
Example(s):
For example, if XYZ organization added
a property to describe the color of
the border on the East side of the
display, they might call it
-xyz-border-east-color.
Other known examples:
-moz-box-sizing
-moz-border-radius
-wap-accesskey
An initial dash or underscore is
guaranteed never to be used in a
property or keyword by any current or
future level of CSS. Thus typical CSS
implementations may not recognize such
properties and may ignore them
according to the rules for handling
parsing errors. However, because the
initial dash or underscore is part of
the grammar, CSS 2.1 implementers
should always be able to use a
CSS-conforming parser, whether or not
they support any vendor-specific
extensions.
Authors should avoid vendor-specific
extensions
The complete regular expression is:
-?(?:[_a-z]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])(?:[_a-z0-9-]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*
So all of your listed characters, except “-” and “_” are not allowed if used directly. But you can encode them using a backslash foo\~bar or using the Unicode notation foo\7E bar.
For those looking for a workaround, you can use an attribute selector, for instance, if your class begins with a number. Change:
.000000-8{background:url(../../images/common/000000-0.8.png);} /* DOESN'T WORK!! */
to this:
[class="000000-8"]{background:url(../../images/common/000000-0.8.png);} /* WORKS :) */
Also, if there are multiple classes, you will need to specify them in selector or use the ~= operator:
[class~="000000-8"]{background:url(../../images/common/000000-0.8.png);}
Sources:
https://benfrain.com/when-and-where-you-can-use-numbers-in-id-and-class-names/
Is there a workaround to make CSS classes with names that start with numbers valid?
https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
My understanding is that the underscore is technically valid. Check out:
https://developer.mozilla.org/en/underscores_in_class_and_id_names
"...errata to the specification published in early 2001 made underscores legal for the first time."
The article linked above says never use them, then gives a list of browsers that don't support them, all of which are, in terms of numbers of users at least, long-redundant.
I would not recommend to use anything except A-z, _- and 0-9, while it's just easier to code with those symbols. Also do not start classes with - while those classes are usually browser-specific flags. To avoid any issues with IDE autocompletion, less complexity when you may need to generate those class names with some other code for whatever reason. Maybe some transpiling software may not work, etc., etc.
Yet CSS is quite loose on this. You can use any symbol, and even emoji works.
<style>
.😭 {
border: 2px solid blue;
width: 100px;
height: 100px;
overflow: hidden;
}
</style>
<div class="😭">
😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅
</div>
We can use all characters in a class name. Even characters like # and .. We just have to escape them with \ (backslash).
.test\.123 {
color: red;
}
.test\#123 {
color: blue;
}
.test\#123 {
color: green;
}
.test\<123 {
color: brown;
}
.test\`123 {
color: purple;
}
.test\~123 {
color: tomato;
}
<div class="test.123">test.123</div>
<div class="test#123">test#123</div>
<div class="test#123">test#123</div>
<div class="test<123">test<123</div>
<div class="test`123">test`123</div>
<div class="test~123">test~123</div>
For HTML5 and CSS 3, classes and IDs can start with numbers.
Going off of Kenan Banks's answer, you can use the following two regex matches to make a string valid:
[^a-z0-9A-Z_-]
This is a reverse match that selects anything that isn't a letter, number, dash or underscore for easy removal.
^-*[0-9]+
This matches 0 or 1 dashes followed by 1 or more numbers at the beginning of a string, also for easy removal.
How I use it in PHP:
// Make alphanumeric with dashes and underscores (removes all other characters)
$class = preg_replace("/[^a-z0-9A-Z_-]/", "", $class);
// Classes only begin with an underscore or letter
$class = preg_replace("/^-*[0-9]+/", "", $class);
// Make sure the string is two or more characters long
return 2 <= strlen($class) ? $class : '';
What characters/symbols are allowed within the CSS class selectors?
I know that the following characters are invalid, but what characters are valid?
~ ! # $ % ^ & * ( ) + = , . / ' ; : " ? > < [ ] \ { } | ` #
You can check directly at the CSS grammar.
Basically1, a name must begin with an underscore (_), a hyphen (-), or a letter(a–z), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must2 be a letter or underscore, and the name must be at least 2 characters long.
-?[_a-zA-Z]+[_a-zA-Z0-9-]*
In short, the previous rule translates to the following, extracted from the W3C specification:
In CSS, identifiers (including element names, classes, and IDs in
selectors) can contain only the characters [a-z0-9] and ISO 10646
characters U+00A0 and higher, plus the hyphen (-) and the underscore
(_); they cannot start with a digit, 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 "B\26 W\3F".
Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in -moz-opacity.
1 It's all made a bit more complicated by the inclusion of escaped Unicode characters (that no one really uses).
2 Note that, according to the grammar I linked, a rule starting with two hyphens, e.g., --indent1, is invalid. However, I'm pretty sure I've seen this in practice.
To my surprise most answers here are wrong. It turns out that:
Any character except NUL is allowed in CSS class names in CSS. (If CSS contains NUL (escaped or not), the result is undefined. [CSS-characters])
Mathias Bynens' answer links to explanation and demos showing how to use these names. Written down in CSS code, a class name may need escaping, but that doesn’t change the class name. E.g. an unnecessarily over-escaped representation will look different from other representations of that name, but it still refers to the same class name.
Most other (programming) languages don’t have that concept of escaping variable names (“identifiers”), so all representations of a variable have to look the same. This is not the case in CSS.
Note that in HTML there is no way to include space characters (space, tab, line feed, form feed and carriage return) in a class name attribute, because they already separate classes from each other.
So, if you need to turn a random string into a CSS class name: take care of NUL and space, and escape (accordingly for CSS or HTML). Done.
I’ve answered your question in-depth at CSS character escape sequences. The article also explains how to escape any character in CSS (and JavaScript), and I made a handy tool for this as well. From that page:
If you were to give an element an ID value of ~!#$%^&*()_+-=,./';:"?><[]{}|`#, the selector would look like this:
CSS:
<style>
#\~\!\#\$\%\^\&\*\(\)\_\+-\=\,\.\/\'\;\:\"\?\>\<\[\]\\\{\}\|\`\#
{
background: hotpink;
}
</style>
JavaScript:
<script>
// document.getElementById or similar
document.getElementById('~!#$%^&*()_+-=,./\';:"?><[]\\{}|`#');
// document.querySelector or similar
$('#\\~\\!\\#\\$\\%\\^\\&\\*\\(\\)\\_\\+-\\=\\,\\.\\/\\\'\\;\\:\\"\\?\\>\\<\\[\\]\\\\\\{\\}\\|\\`\\#');
</script>
Read the W3C spec. (this is CSS 2.1; find the appropriate version for your assumption of browsers)
relevant paragraph:
In CSS, identifiers (including
element names, classes, and IDs in
selectors) can contain only the
characters [a-z0-9] and ISO 10646
characters U+00A1 and higher, plus the
hyphen (-) and the underscore (_);
they cannot start with a digit, 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 "B\26 W\3F".
As #mipadi points out in Kenan Banks's answer, there's this caveat, also in the same webpage:
In CSS, identifiers may begin with '-'
(dash) or '_' (underscore). Keywords
and property names beginning with '-'
or '_' are reserved for
vendor-specific extensions. Such
vendor-specific extensions should have
one of the following formats:
'-' + vendor identifier + '-' + meaningful name
'_' + vendor identifier + '-' + meaningful name
Example(s):
For example, if XYZ organization added
a property to describe the color of
the border on the East side of the
display, they might call it
-xyz-border-east-color.
Other known examples:
-moz-box-sizing
-moz-border-radius
-wap-accesskey
An initial dash or underscore is
guaranteed never to be used in a
property or keyword by any current or
future level of CSS. Thus typical CSS
implementations may not recognize such
properties and may ignore them
according to the rules for handling
parsing errors. However, because the
initial dash or underscore is part of
the grammar, CSS 2.1 implementers
should always be able to use a
CSS-conforming parser, whether or not
they support any vendor-specific
extensions.
Authors should avoid vendor-specific
extensions
The complete regular expression is:
-?(?:[_a-z]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])(?:[_a-z0-9-]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*
So all of your listed characters, except “-” and “_” are not allowed if used directly. But you can encode them using a backslash foo\~bar or using the Unicode notation foo\7E bar.
For those looking for a workaround, you can use an attribute selector, for instance, if your class begins with a number. Change:
.000000-8{background:url(../../images/common/000000-0.8.png);} /* DOESN'T WORK!! */
to this:
[class="000000-8"]{background:url(../../images/common/000000-0.8.png);} /* WORKS :) */
Also, if there are multiple classes, you will need to specify them in selector or use the ~= operator:
[class~="000000-8"]{background:url(../../images/common/000000-0.8.png);}
Sources:
https://benfrain.com/when-and-where-you-can-use-numbers-in-id-and-class-names/
Is there a workaround to make CSS classes with names that start with numbers valid?
https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
My understanding is that the underscore is technically valid. Check out:
https://developer.mozilla.org/en/underscores_in_class_and_id_names
"...errata to the specification published in early 2001 made underscores legal for the first time."
The article linked above says never use them, then gives a list of browsers that don't support them, all of which are, in terms of numbers of users at least, long-redundant.
I would not recommend to use anything except A-z, _- and 0-9, while it's just easier to code with those symbols. Also do not start classes with - while those classes are usually browser-specific flags. To avoid any issues with IDE autocompletion, less complexity when you may need to generate those class names with some other code for whatever reason. Maybe some transpiling software may not work, etc., etc.
Yet CSS is quite loose on this. You can use any symbol, and even emoji works.
<style>
.😭 {
border: 2px solid blue;
width: 100px;
height: 100px;
overflow: hidden;
}
</style>
<div class="😭">
😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅😅
</div>
We can use all characters in a class name. Even characters like # and .. We just have to escape them with \ (backslash).
.test\.123 {
color: red;
}
.test\#123 {
color: blue;
}
.test\#123 {
color: green;
}
.test\<123 {
color: brown;
}
.test\`123 {
color: purple;
}
.test\~123 {
color: tomato;
}
<div class="test.123">test.123</div>
<div class="test#123">test#123</div>
<div class="test#123">test#123</div>
<div class="test<123">test<123</div>
<div class="test`123">test`123</div>
<div class="test~123">test~123</div>
For HTML5 and CSS 3, classes and IDs can start with numbers.
Going off of Kenan Banks's answer, you can use the following two regex matches to make a string valid:
[^a-z0-9A-Z_-]
This is a reverse match that selects anything that isn't a letter, number, dash or underscore for easy removal.
^-*[0-9]+
This matches 0 or 1 dashes followed by 1 or more numbers at the beginning of a string, also for easy removal.
How I use it in PHP:
// Make alphanumeric with dashes and underscores (removes all other characters)
$class = preg_replace("/[^a-z0-9A-Z_-]/", "", $class);
// Classes only begin with an underscore or letter
$class = preg_replace("/^-*[0-9]+/", "", $class);
// Make sure the string is two or more characters long
return 2 <= strlen($class) ? $class : '';
When creating the id attributes for HTML elements, what rules are there for the value?
For HTML 4, the answer is technically:
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 (".").
HTML 5 is even more permissive, saying only that an id must contain at least one character and may not contain any space characters.
The id attribute is case sensitive in XHTML.
As a purely practical matter, you may want to avoid certain characters. Periods, colons and '#' have special meaning in CSS selectors, so you will have to escape those characters using a backslash in CSS or a double backslash in a selector string passed to jQuery. Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids.
For example, the HTML declaration <div id="first.name"></div> is valid. You can select that element in CSS as #first\.name and in jQuery like so: $('#first\\.name'). But if you forget the backslash, $('#first.name'), you will have a perfectly valid selector looking for an element with id first and also having class name. This is a bug that is easy to overlook. You might be happier in the long run choosing the id first-name (a hyphen rather than a period), instead.
You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder "was it firstName or FirstName?" because you will always know that you should type first_name. Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don't mix them.
A now very obscure problem was that at least one browser, Netscape 6, incorrectly treated id attribute values as case-sensitive. That meant that if you had typed id="firstName" in your HTML (lower-case 'f') and #FirstName { color: red } in your CSS (upper-case 'F'), that buggy browser would have failed to set the element's color to red. At the time of this edit, April 2015, I hope you aren't being asked to support Netscape 6. Consider this a historical footnote.
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 (".").
A common mistake is to use an ID that starts with a digit.
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:
#my.cool:thing { ... /* some rules */ ... }
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.
HTML5: Permitted Values for ID & Class Attributes
As of HTML5, the only restrictions on the value of an ID are:
must be unique in the document
must not contain any space characters
must contain at least one character
Similar rules apply to classes (except for the uniqueness, of course).
So the value can be all digits, just one digit, just punctuation characters, include special characters, whatever. Just no whitespace. This is very different from HTML4.
In HTML 4, ID values must begin with a letter, which can then be followed only by letters, digits, hyphens, underscores, colons and periods.
In HTML5 these are valid:
<div id="999"> ... </div>
<div id="#%LV-||"> ... </div>
<div id="____V"> ... </div>
<div id="⌘⌥"> ... </div>
<div id="♥"> ... </div>
<div id="{}"> ... </div>
<div id="©"> ... </div>
<div id="♤₩¤☆€~¥"> ... </div>
Just bear in mind that using numbers, punctuation or special characters in the value of an ID may cause trouble in other contexts (e.g., CSS, JavaScript, regex).
For example, the following ID is valid in HTML5:
<div id="9lions"> ... </div>
However, it is invalid in CSS:
From the CSS2.1 spec:
4.1.3 Characters and case
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.
In most cases you may be able to escape characters in contexts where they have restrictions or special meaning.
W3C References
HTML5
3.2.5.1 The id
attribute
The id attribute specifies its element's unique identifier (ID).
The value must be unique amongst all the IDs in the element's home
subtree and must contain at least one character. The value must not
contain any space characters.
Note: There are no other restrictions on what form an ID can take; in
particular, IDs can consist of just digits, start with a digit, start
with an underscore, consist of just punctuation, etc.
3.2.5.7 The class
attribute
The attribute, if specified, must have a value that is a set of
space-separated tokens representing the various classes that the
element belongs to.
The classes that an HTML element has assigned to it consists of all
the classes returned when the value of the class attribute is split on
spaces. (Duplicates are ignored.)
There are no additional restrictions on the tokens authors can use in
the class attribute, but authors are encouraged to use values that
describe the nature of the content, rather than values that describe
the desired presentation of the content.
jQuery does handle any valid ID name. You just need to escape metacharacters (i.e., dots, semicolons, square brackets...). It's like saying that JavaScript has a problem with quotes only because you can't write
var name = 'O'Hara';
Selectors in jQuery API (see bottom note)
Strictly it should match
[A-Za-z][-A-Za-z0-9_:.]*
But jQuery seems to have problems with colons, so it might be better to avoid them.
HTML5:
It gets rid of the additional restrictions on the id attribute (see here). The only requirements left (apart from being unique in the document) are:
the value must contain at least one character (can’t be empty)
it can’t contain any space characters.
Pre-HTML5:
ID should match:
[A-Za-z][-A-Za-z0-9_:.]*
Must start with A-Z or a-z characters
May contain - (hyphen), _ (underscore), : (colon) and . (period)
But one should avoid : and . because:
For example, an ID could be labelled "a.b:c" and referenced in the style sheet as #a.b:c, but as well as being the id for the element, it could mean id "a", class "b", pseudo-selector "c". It is best to avoid the confusion and stay away from using . and : altogether.
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 and name attributes: they are now just opaque strings which cannot contain spaces.
Hyphens, underscores, periods, colons, numbers and letters are all valid for use with CSS and jQuery. The following should work, but it must be unique throughout the page and also must start with a letter [A-Za-z].
Working with colons and periods needs a bit more work, but you can do it as the following example shows.
<html>
<head>
<title>Cake</title>
<style type="text/css">
#i\.Really\.Like\.Cake {
color: green;
}
#i\:Really\:Like\:Cake {
color: blue;
}
</style>
</head>
<body>
<div id="i.Really.Like.Cake">Cake</div>
<div id="testResultPeriod"></div>
<div id="i:Really:Like:Cake">Cake</div>
<div id="testResultColon"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var testPeriod = $("#i\\.Really\\.Like\\.Cake");
$("#testResultPeriod").html("found " + testPeriod.length + " result.");
var testColon = $("#i\\:Really\\:Like\\:Cake");
$("#testResultColon").html("found " + testColon.length + " result.");
});
</script>
</body>
</html>
HTML5
Keeping in mind that ID must be unique, i.e., there must not be multiple elements in a document that have the same id value.
The rules about ID content in HTML5 are (apart from being unique):
This attribute's value must not contain white spaces. [...]
Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
This is the W3 spec about ID (from MDN):
Any string, with the following restrictions:
must be at least one character long
must not contain any space characters
Previous versions of HTML placed greater restrictions on the content of ID values (for example, they did not permit ID values to begin with a number).
More information:
W3 - global attributes (id)
MDN attribute (id)
To reference an id with a period in it, you need to use a backslash. I am not sure if it's the same for hyphens or underscores.
For example:
HTML
<div id="maintenance.instrumentNumber">############0218</div>
CSS
#maintenance\.instrumentNumber{word-wrap:break-word;}
From the HTML 4 specification...
The 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 (".").
Also, never forget that an ID is unique. Once used, the ID value may not appear again anywhere in the document.
You may have many ID's, but all must have a unique value.
On the other hand, there is the class-element. Just like ID, it can appear many times, but the value may be used over and over again.
A unique identifier for the element.
There must not be multiple elements in a document that have the same id value.
Any string, with the following restrictions:
must be at least one character long
must not contain any space characters:
U+0020 SPACE
U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+000D CARRIAGE RETURN (CR)
Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
It appears that, although colons (:) and periods (.) are valid in the HTML specification, they are invalid as id selectors in CSS, so they are probably best avoided if you intend to use them for that purpose.
For HTML5:
The value must be unique amongst all the IDs in the element’s home
subtree and must contain at least one character. The value must not
contain any space characters.
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.
IDs are best suited for naming parts of your layout, so you should not give the same name for ID and class
ID allows alphanumeric and special characters
but avoid using the # : . * ! symbols
spaces are not allowed
not started with numbers or a hyphen followed by a digit
case sensitive
using ID selectors is faster than using class selectors
use hyphen "-" (underscore "_" can also be used, but it is not good for SEO) for long CSS class or Id rule names
If a rule has an ID selector as its key selector, don’t add the tag name to the rule. Since IDs are unique, adding a tag name would slow down the matching process needlessly.
In HTML5, the id attribute can be used on any HTML element and In HTML 4.01, the id attribute cannot be used with: <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>.
Any alpha-numeric value,"-", and "_" are valid. But, you should start the id name with any character between A-Z or a-z.
Since ES2015 we can as well use almost all Unicode characters for ID's, if the document character set is set to UTF-8.
Test out here: https://mothereff.in/js-variables
Read about it: Valid JavaScript variable names in ES2015
In ES2015, identifiers must start with $, _, or any symbol with the
Unicode derived core property ID_Start.
The rest of the identifier can contain $, _, U+200C zero width
non-joiner, U+200D zero width joiner, or any symbol with the Unicode
derived core property ID_Continue.
const target = document.querySelector("div").id
console.log("Div id:", target )
document.getElementById(target).style.background = "chartreuse"
div {
border: 5px blue solid;
width: 100%;
height: 200px
}
<div id="H̹̙̦̮͉̩̗̗ͧ̇̏̊̾Eͨ͆͒̆ͮ̃͏̷̮̣̫̤̣Cͯ̂͐͏̨̛͔̦̟͈̻O̜͎͍͙͚̬̝̣̽ͮ͐͗̀ͤ̍̀͢M̴̡̲̭͍͇̼̟̯̦̉̒͠Ḛ̛̙̞̪̗ͥͤͩ̾͑̔͐ͅṮ̴̷̷̗̼͍̿̿̓̽͐H̙̙̔̄͜"></div>
Should you use it? Probably not a good idea!
Read about it: JavaScript: "Syntax error missing } after function body"
No spaces, and it must begin with at least a character from a to z and 0 to 9.
In HTML
ID should start with {A-Z} or {a-z}. You can add digits, periods, hyphens, underscores, and colons.
For example:
<span id="testID2"></span>
<span id="test-ID2"></span>
<span id="test_ID2"></span>
<span id="test:ID2"></span>
<span id="test.ID2"></span>
But even though you can make ID with colons (:) or period (.). It is hard for CSS to use these IDs as a selector. Mainly when you want to use pseudo elements (:before and :after).
Also in JavaScript it is hard to select these ID's.
So you should use first four ID's as the preferred way by many developers around and if it's necessary then you can use the last two also.
Walues can be: [a-z], [A-Z], [0-9], [* _ : -]
It is used for HTML5...
We can add id with any tag.
Help, my Javascript is broken!
Everyone says IDs can't be duplicates.
Best tried in every browser but FireFox
<div id="ONE"></div>
<div id="ONE"></div>
<div id="ONE"></div>
<script>
document.body.append( document.querySelectorAll("#ONE").length , ' DIVs!')
document.body.append( ' in a ', typeof ONE )
console.log( ONE ); // a global var !!
</script>
Explanation
After the turn of the century Microsoft had 90% Browser Market share,
and implemented Browser behaviours that where never standardized:
1. create global variables for every ID
2. create an Array for duplicate IDs
All later Browser vendors copied this behaviour, otherwise their browser wouldn't support older sites.
Somewhere around 2015 Mozilla removed 2. from FireFox and 1. still works.
All other browsers still do 1. and 2.
I use it every day because typing ONE instead of document.querySelector("#ONE") helps me prototype faster; I do not use it in production.
Html ID
The id attribute specifies its element's unique identifier (ID).
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
An element's unique identifier can be used for a variety of purposes, most notably as a way to link to specific parts of a document using fragments, as a way to target an element when scripting, and as a way to style a specific element from CSS.
Uppercase and lowercase alphabets works
'_' and '-' works, too
Numbers works
Colons (,) and period (.) seems to work
Interestingly, emojis work
alphabets → caps & small
digits → 0-9
special characters → ':', '-', '_', '.'
The format should be either starting from '.' or an alphabet, followed by either of the special characters of more alphabets or numbers. The value of the id field must not end at an '_'.
Also, spaces are not allowed, if provided, they are treated as different values, which is not valid in case of the id attributes.
When creating the id attributes for HTML elements, what rules are there for the value?
For HTML 4, the answer is technically:
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 (".").
HTML 5 is even more permissive, saying only that an id must contain at least one character and may not contain any space characters.
The id attribute is case sensitive in XHTML.
As a purely practical matter, you may want to avoid certain characters. Periods, colons and '#' have special meaning in CSS selectors, so you will have to escape those characters using a backslash in CSS or a double backslash in a selector string passed to jQuery. Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids.
For example, the HTML declaration <div id="first.name"></div> is valid. You can select that element in CSS as #first\.name and in jQuery like so: $('#first\\.name'). But if you forget the backslash, $('#first.name'), you will have a perfectly valid selector looking for an element with id first and also having class name. This is a bug that is easy to overlook. You might be happier in the long run choosing the id first-name (a hyphen rather than a period), instead.
You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder "was it firstName or FirstName?" because you will always know that you should type first_name. Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don't mix them.
A now very obscure problem was that at least one browser, Netscape 6, incorrectly treated id attribute values as case-sensitive. That meant that if you had typed id="firstName" in your HTML (lower-case 'f') and #FirstName { color: red } in your CSS (upper-case 'F'), that buggy browser would have failed to set the element's color to red. At the time of this edit, April 2015, I hope you aren't being asked to support Netscape 6. Consider this a historical footnote.
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 (".").
A common mistake is to use an ID that starts with a digit.
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:
#my.cool:thing { ... /* some rules */ ... }
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.
HTML5: Permitted Values for ID & Class Attributes
As of HTML5, the only restrictions on the value of an ID are:
must be unique in the document
must not contain any space characters
must contain at least one character
Similar rules apply to classes (except for the uniqueness, of course).
So the value can be all digits, just one digit, just punctuation characters, include special characters, whatever. Just no whitespace. This is very different from HTML4.
In HTML 4, ID values must begin with a letter, which can then be followed only by letters, digits, hyphens, underscores, colons and periods.
In HTML5 these are valid:
<div id="999"> ... </div>
<div id="#%LV-||"> ... </div>
<div id="____V"> ... </div>
<div id="⌘⌥"> ... </div>
<div id="♥"> ... </div>
<div id="{}"> ... </div>
<div id="©"> ... </div>
<div id="♤₩¤☆€~¥"> ... </div>
Just bear in mind that using numbers, punctuation or special characters in the value of an ID may cause trouble in other contexts (e.g., CSS, JavaScript, regex).
For example, the following ID is valid in HTML5:
<div id="9lions"> ... </div>
However, it is invalid in CSS:
From the CSS2.1 spec:
4.1.3 Characters and case
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.
In most cases you may be able to escape characters in contexts where they have restrictions or special meaning.
W3C References
HTML5
3.2.5.1 The id
attribute
The id attribute specifies its element's unique identifier (ID).
The value must be unique amongst all the IDs in the element's home
subtree and must contain at least one character. The value must not
contain any space characters.
Note: There are no other restrictions on what form an ID can take; in
particular, IDs can consist of just digits, start with a digit, start
with an underscore, consist of just punctuation, etc.
3.2.5.7 The class
attribute
The attribute, if specified, must have a value that is a set of
space-separated tokens representing the various classes that the
element belongs to.
The classes that an HTML element has assigned to it consists of all
the classes returned when the value of the class attribute is split on
spaces. (Duplicates are ignored.)
There are no additional restrictions on the tokens authors can use in
the class attribute, but authors are encouraged to use values that
describe the nature of the content, rather than values that describe
the desired presentation of the content.
jQuery does handle any valid ID name. You just need to escape metacharacters (i.e., dots, semicolons, square brackets...). It's like saying that JavaScript has a problem with quotes only because you can't write
var name = 'O'Hara';
Selectors in jQuery API (see bottom note)
Strictly it should match
[A-Za-z][-A-Za-z0-9_:.]*
But jQuery seems to have problems with colons, so it might be better to avoid them.
HTML5:
It gets rid of the additional restrictions on the id attribute (see here). The only requirements left (apart from being unique in the document) are:
the value must contain at least one character (can’t be empty)
it can’t contain any space characters.
Pre-HTML5:
ID should match:
[A-Za-z][-A-Za-z0-9_:.]*
Must start with A-Z or a-z characters
May contain - (hyphen), _ (underscore), : (colon) and . (period)
But one should avoid : and . because:
For example, an ID could be labelled "a.b:c" and referenced in the style sheet as #a.b:c, but as well as being the id for the element, it could mean id "a", class "b", pseudo-selector "c". It is best to avoid the confusion and stay away from using . and : altogether.
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 and name attributes: they are now just opaque strings which cannot contain spaces.
Hyphens, underscores, periods, colons, numbers and letters are all valid for use with CSS and jQuery. The following should work, but it must be unique throughout the page and also must start with a letter [A-Za-z].
Working with colons and periods needs a bit more work, but you can do it as the following example shows.
<html>
<head>
<title>Cake</title>
<style type="text/css">
#i\.Really\.Like\.Cake {
color: green;
}
#i\:Really\:Like\:Cake {
color: blue;
}
</style>
</head>
<body>
<div id="i.Really.Like.Cake">Cake</div>
<div id="testResultPeriod"></div>
<div id="i:Really:Like:Cake">Cake</div>
<div id="testResultColon"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var testPeriod = $("#i\\.Really\\.Like\\.Cake");
$("#testResultPeriod").html("found " + testPeriod.length + " result.");
var testColon = $("#i\\:Really\\:Like\\:Cake");
$("#testResultColon").html("found " + testColon.length + " result.");
});
</script>
</body>
</html>
HTML5
Keeping in mind that ID must be unique, i.e., there must not be multiple elements in a document that have the same id value.
The rules about ID content in HTML5 are (apart from being unique):
This attribute's value must not contain white spaces. [...]
Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
This is the W3 spec about ID (from MDN):
Any string, with the following restrictions:
must be at least one character long
must not contain any space characters
Previous versions of HTML placed greater restrictions on the content of ID values (for example, they did not permit ID values to begin with a number).
More information:
W3 - global attributes (id)
MDN attribute (id)
To reference an id with a period in it, you need to use a backslash. I am not sure if it's the same for hyphens or underscores.
For example:
HTML
<div id="maintenance.instrumentNumber">############0218</div>
CSS
#maintenance\.instrumentNumber{word-wrap:break-word;}
From the HTML 4 specification...
The 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 (".").
Also, never forget that an ID is unique. Once used, the ID value may not appear again anywhere in the document.
You may have many ID's, but all must have a unique value.
On the other hand, there is the class-element. Just like ID, it can appear many times, but the value may be used over and over again.
A unique identifier for the element.
There must not be multiple elements in a document that have the same id value.
Any string, with the following restrictions:
must be at least one character long
must not contain any space characters:
U+0020 SPACE
U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+000D CARRIAGE RETURN (CR)
Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
It appears that, although colons (:) and periods (.) are valid in the HTML specification, they are invalid as id selectors in CSS, so they are probably best avoided if you intend to use them for that purpose.
For HTML5:
The value must be unique amongst all the IDs in the element’s home
subtree and must contain at least one character. The value must not
contain any space characters.
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.
IDs are best suited for naming parts of your layout, so you should not give the same name for ID and class
ID allows alphanumeric and special characters
but avoid using the # : . * ! symbols
spaces are not allowed
not started with numbers or a hyphen followed by a digit
case sensitive
using ID selectors is faster than using class selectors
use hyphen "-" (underscore "_" can also be used, but it is not good for SEO) for long CSS class or Id rule names
If a rule has an ID selector as its key selector, don’t add the tag name to the rule. Since IDs are unique, adding a tag name would slow down the matching process needlessly.
In HTML5, the id attribute can be used on any HTML element and In HTML 4.01, the id attribute cannot be used with: <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>.
Any alpha-numeric value,"-", and "_" are valid. But, you should start the id name with any character between A-Z or a-z.
Since ES2015 we can as well use almost all Unicode characters for ID's, if the document character set is set to UTF-8.
Test out here: https://mothereff.in/js-variables
Read about it: Valid JavaScript variable names in ES2015
In ES2015, identifiers must start with $, _, or any symbol with the
Unicode derived core property ID_Start.
The rest of the identifier can contain $, _, U+200C zero width
non-joiner, U+200D zero width joiner, or any symbol with the Unicode
derived core property ID_Continue.
const target = document.querySelector("div").id
console.log("Div id:", target )
document.getElementById(target).style.background = "chartreuse"
div {
border: 5px blue solid;
width: 100%;
height: 200px
}
<div id="H̹̙̦̮͉̩̗̗ͧ̇̏̊̾Eͨ͆͒̆ͮ̃͏̷̮̣̫̤̣Cͯ̂͐͏̨̛͔̦̟͈̻O̜͎͍͙͚̬̝̣̽ͮ͐͗̀ͤ̍̀͢M̴̡̲̭͍͇̼̟̯̦̉̒͠Ḛ̛̙̞̪̗ͥͤͩ̾͑̔͐ͅṮ̴̷̷̗̼͍̿̿̓̽͐H̙̙̔̄͜"></div>
Should you use it? Probably not a good idea!
Read about it: JavaScript: "Syntax error missing } after function body"
No spaces, and it must begin with at least a character from a to z and 0 to 9.
In HTML
ID should start with {A-Z} or {a-z}. You can add digits, periods, hyphens, underscores, and colons.
For example:
<span id="testID2"></span>
<span id="test-ID2"></span>
<span id="test_ID2"></span>
<span id="test:ID2"></span>
<span id="test.ID2"></span>
But even though you can make ID with colons (:) or period (.). It is hard for CSS to use these IDs as a selector. Mainly when you want to use pseudo elements (:before and :after).
Also in JavaScript it is hard to select these ID's.
So you should use first four ID's as the preferred way by many developers around and if it's necessary then you can use the last two also.
Walues can be: [a-z], [A-Z], [0-9], [* _ : -]
It is used for HTML5...
We can add id with any tag.
Help, my Javascript is broken!
Everyone says IDs can't be duplicates.
Best tried in every browser but FireFox
<div id="ONE"></div>
<div id="ONE"></div>
<div id="ONE"></div>
<script>
document.body.append( document.querySelectorAll("#ONE").length , ' DIVs!')
document.body.append( ' in a ', typeof ONE )
console.log( ONE ); // a global var !!
</script>
Explanation
After the turn of the century Microsoft had 90% Browser Market share,
and implemented Browser behaviours that where never standardized:
1. create global variables for every ID
2. create an Array for duplicate IDs
All later Browser vendors copied this behaviour, otherwise their browser wouldn't support older sites.
Somewhere around 2015 Mozilla removed 2. from FireFox and 1. still works.
All other browsers still do 1. and 2.
I use it every day because typing ONE instead of document.querySelector("#ONE") helps me prototype faster; I do not use it in production.
Html ID
The id attribute specifies its element's unique identifier (ID).
There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.
An element's unique identifier can be used for a variety of purposes, most notably as a way to link to specific parts of a document using fragments, as a way to target an element when scripting, and as a way to style a specific element from CSS.
Uppercase and lowercase alphabets works
'_' and '-' works, too
Numbers works
Colons (,) and period (.) seems to work
Interestingly, emojis work
alphabets → caps & small
digits → 0-9
special characters → ':', '-', '_', '.'
The format should be either starting from '.' or an alphabet, followed by either of the special characters of more alphabets or numbers. The value of the id field must not end at an '_'.
Also, spaces are not allowed, if provided, they are treated as different values, which is not valid in case of the id attributes.