By Mr Shark

2008-09-16 09:08:52 8 Comments

When creating the id attributes for HTML elements, what rules are there for the value?


@a.miadian 2018-10-19 17:08:21

I know this is very late for answering to this question, but because of I had the same problem and I find this answer more complete, I decide to answer.

All of a,b,c...x,y,z,A,B,C...X,Y,Z,0,1,2...7,8,9,-,_ can use for id, but you should not use digit and - as first character.

these are wrong:

1adfsvsdf   // use number in first
-adfasdf    // use - in first
afd'ksdf    // use ' in characters
asdf;asdf   // use ; in characters

@dgvid 2008-09-17 01:42:42

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=""></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, $(''), 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.

@John Topley 2009-04-22 10:35:58

Note that class and id attributes are case-sensitive in XHTML, all other attributes are not. Eric Meyer mentioned this in a CSS workshop I attended.

@Zack The Human 2010-01-20 00:53:18

Also note that if you try to write a CSS rule to target an element by ID, and the ID beings with a number, it won't work. Bummer!

@Wolfram 2010-05-06 10:18:49

As for '.' or ':' in an ID using jQuery, see the jQuery FAQ. It contains a small function that does the necessary escaping.

@Augustus Kling 2011-09-30 07:55:57

The id attribute is [](case sensitive in HTML4) and has to begin with a letter (limited to A to Z). Also note that your example should not make your element's text color red since your CSS refers to an element with class FirstName not to your id.

@dgvid 2011-09-30 13:36:07

I've just updated the response to include a mention of HTML 5's more permissive rules and fixed that error in my CSS example. Thanks for the comments everyone!

@Stephen Booher 2012-01-26 17:15:44

The error that Augustus pointed out is still present. In your example, if you have id="firstName" in either HTML 4 or HTML 5 and #FirstName { color: red } in CSS, only a buggy browser will set the element's color to red.

@verdy_p 2012-03-21 14:43:16

Actually identifiers in HTML/XML are not restricted to only ASCII letters, digits, hyphens and underscores. All other Latin letters are also valid (for example "Café" is a valid HTML/XML identifier). And in fact you can use letters from any alphabet of any simple alphabetic script (for example Greek, Cyrillic, Armenian, or Georgian letters)

@verdy_p 2012-03-21 14:47:34

And in fact you can use letters from any alphabet of any simple alphabetic script (for example Greek, Cyrillic, Armenian, or Georgian letters), or syllabaries (such Japanese kanas), or sinograms. You may also include combining characters (such as an Hebrew point) in your identifiers (but not as their first character), as well as other Unicode joiners (such as ZWJ and ZWNJ) (only before another letter, but not at the start of the identifier).

@verdy_p 2012-03-21 14:49:27

Digits for other scripts are also accepted (for example Devanagari digits). Some other hyphens are also accepted (such as the Arabic Kashida). Only letters and digits defined as compatibility characters (such as contextual & form variants) are not allowed. You may as well insert Read the XML and HTML specifications about which letters scripts are acceptable.

@verdy_p 2012-03-21 16:24:47

Here are the allowed characters: ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]

@verdy_p 2012-03-21 16:27:28

All those characters can occur anywhere in a "Name" production, to which an ID type must obey. However the first character is more restricted, and the following additional characters can only occur starting at the second character: "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]

@verdy_p 2012-03-21 16:28:57

Some of these characters are normally forbidden literally in CSS selectors, and have to be escaped (this is the case of the dot '.'

@verdy_p 2012-03-21 16:33:15

This also means that many punctuations and symbols are usable as well (for example the Euro symbol '€', U+20AC, falls in the list of characters allowed everywhere in an ID, so '€' is a valid id, but not '$' which is valid in Javascript identifiers but not in HTML/XML identifiers !)

@verdy_p 2012-03-21 16:38:11

Note that you may also use character references in an ID: "&#x41;" is as valid as "A". Note also that all chracters in supplementary planes except PUA planes are valid. This also means that the id '&#x10FFFF;' is a valid, even if an HTML/XML document cannot be encoded as plain-text if you substitute the character reference by its literal character: the document would no longer be plain-text because it contains a "non-character".

@verdy_p 2012-03-21 16:52:34

Note also that IDs do not have to be in normalical canonical form: even if two id's are canonically equivalene (they have the same NFC form), they are considered distint. XML and HTML do not perform normalizations on textual element names, attribute names, ID's, name tokens, attribute values of any type, and contents of text elements.

@verdy_p 2012-03-21 16:54:27

You'll note that general combining characters in the range [#x0300-#x036F] are not allowed at the start of an id, but combining characters and format controls of many scripts are permitted. So an identifier made only of a combining acute accent is invalid, but an identifier made only of a combining Arabic Sukun is valid, even if it makes no sense in Arabic !!!

@verdy_p 2012-03-21 17:19:14

Note finally that those restrictions were needed for compatibility with XHTML, i.e. finally with XML. But in HTML5, the compatibility with XML and XHTML is not required, and in fact HTML5 does not even contain elements requiring the use of the "xml:" namespace or any other namespace. In HTML5 the standard "id" attribute is now simply an opaque string without any other restriction than not containing any space. So the attribute id="Have'a'good&nbsp;day!" is perfectly valid in HTML5, but would be invalid in XHTML due to the non-breaking space and the quotes...

@Buttle Butkus 2014-11-14 23:12:42

To get selectors to work in jQuery, for some characters all you need to do is add "\\" (2 slashes) just before the problem character. Here is the link to an escape function for periods and colons in a jquery selector:… and here is the function function jq( myid ) {return "#" + myid.replace( /(:|\.|\[|\])/g, "\\$1" );}

@Tomáš Zato 2014-12-01 22:43:19

Is there any length limit?

@Kira 2015-01-08 11:07:39

@dgvid, will browser throw error if syntax for id attribute breached ?

@dgvid 2015-01-08 20:00:03

Each browser may handle an invalid id in its own way. In general, browsers try to be forgiving of syntax errors, so an invalid id might break the page in some way, but give no other indication of an error.

@T.J. Crowder 2015-03-30 21:49:47

"However, as a practical matter, you will be somewhat more limited if you want your documents to work with a variety of browsers, CSS editors, and JavaScript frameworks." Citation? Examples? What browsers? What editors? "As noted in other responses, jQuery has problems with ids that contain periods and colons." Does it? What problems? jQuery works with correct CSS selectors, and correct CSS selectors can select elements with all-numeric ids (you just have to escape them correctly, which is defined in CSS). What "problems" are you talking about?

@thdoan 2015-04-27 03:31:36

Keep in mind that #3d { background:red; } won't work (hence don't use an 'id' that starts with a number if you want to style it).

@Oliver Ni 2017-08-12 09:33:55

I prefer first-name.

@Jeff Xiao 2018-02-07 15:06:18

just from a convenience's point of view, you can select the text of first_name with double-click, but not first-name

@Mr Lister 2018-02-26 14:26:48

@10basetom You can always escape the first character: \33 d.

@Wembo Mulumba 2017-05-09 04:22:32

No spaces, must begin with at least a char from a to z and 0 to 9.

@Michael_B 2015-08-02 15:53:16

HTML5: Permitted Values for ID & Class Attributes

As of HTML5, the only restrictions on the value of an ID are:

  1. must be unique in the document
  2. must not contain any space characters
  3. 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 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. 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.

@Tazwar Utshas 2016-11-12 13:52:52

Any Alpha-numeric value and "-" and "_" is valid. But, you should start the id name with any character between A-Z or a-z.

@Bhavin Solanki 2016-07-15 13:02:03

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:

  1. must be at least one character long
  2. must not contain any space characters:

    • U+0020 SPACE
    • U+000A LINE FEED (LF)
    • U+000C FORM FEED (FF)

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.

@Zaheer Ahmed 2013-01-18 07:09:23


gets rid of the additional restrictions on the id attribute see here. The only requirements left (apart from being unique in the document) are:

  1. the value must contain at least one character (can’t be empty)
  2. it can’t contain any space characters.


ID should match:

  1. Must Start with A-Z or a-z characters
  2. May contain - (hyphen), _ (underscore), : (colon) and . (period)

but one should avoid : and . beacause:

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". Best to avoid the confusion and stay away from using . and : altogether.

@user3968801 2014-09-13 20:17:54

In HTML5, an id can't start with a number, e.g. id-"1kid" and they can't have spaces (id="Some kind")

@Andrew Barber 2014-09-16 19:22:58

This is wrong. See here: "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."

@Michael Thompson 2008-09-16 14:01:21

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 "", your CSS selector will look like this: { ... /* 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.

@joeformd 2009-12-03 10:41:33

You can use colons and periods - but you'll need to escape them using double backslashes, eg: $('#my\\.cool\\:thing') or escaping a variable: $('#'+id.replace(/\./,’\\.’).replace(/\:/,’\\:’))…

@cori 2011-05-02 16:35:23

Why not numerals; why just A-Z? Numbers are very useful IDs when referring to elements that are related to data that's keyed with a number, as long as you don't start with the number.

@Tony 2011-07-08 18:31:44

Just FYI, dashes are technically hyphens. Minus sign isn't in ASCII character set.

@vol7ron 2011-10-18 16:57:25

@jowformd: interesting idea using replace in the selector, instead of using the function twice, why not just improve the regex id.replace(/([\.:])/g,"\\$1")

@Faust 2013-06-07 07:36:05

If you have these characters (., :) in ids, and cannot remove them (cough ... Sharepoint), you can get around this in CSS with attribute selectors instead of id selectors, e.g. [id=''], however this selector will have a lower specificity than an id selector, which might cause other problems.

@Michael Thompson 2013-12-30 15:03:33

Old, I know, but updated to include numbers and backpedal on hyphens

@Anthony 2013-11-13 20:14:15

To reference an id with a period in it you need to use a backslash. Not sure if its the same for hyphens or underscores. For example: HTML

<div id="maintenance.instrumentNumber">############0218</div>



@MrWhite 2013-11-14 01:25:30

Hyphens and underscores don't normally need to be escaped. However, the exception to this is if the hyphen appears at the start of the identifier and is followed by another hyphen (eg. \--abc) or a digit (eg. \-123).

@Sergio 2013-08-26 21:54:46


Keeping in mind that ID must be unique, ie. 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 (från 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 info:

  • W3 - global attributes (id)
  • MDN atribute (id)

@Kanishka Panamaldeniya 2013-08-21 10:57:06

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.

@Web Designer cum Promoter 2013-05-02 06:28:33

  1. IDs are best suited for naming parts of your layout so should not give same name for ID and class
  2. ID allows alphanumeric and special characters
  3. but avoid using of # : . * ! symbols
  4. not allowed spaces
  5. not started with numbers or a hyphen followed by a digit
  6. case sensitive
  7. using ID selectors is faster than using class selectors
  8. use hyphen "-" (underscore "_" can also use but not good for seo) for long CSS class or Id rule names
  9. 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.
  10. 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>.

@Nick Rice 2016-05-07 16:55:45

"underscore can also use but not good for seo": Since when did search engines take any interest in CSS class or id names?

@Shashank N. Pandey 2012-09-22 18:27:51

alphabets-> caps & small
digits-> 0-9
special chars-> ':', '-', '_', '.'

the format should be either starting from '.' or an alphabet, followed by either of the special chars 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.

@Mr Shark 2008-09-16 09:11:25

Strictly it should match


But jquery seems to have problems with colons so it might be better to avoid them.

@foo 2011-01-07 05:09:32

shouldn't that be [A-Za-z][-A-Za-z0-9_:.]* instead, since everything after the first letter is optional ("any number" includes zero, "may" implies "does not have to").

@Vordreller 2008-09-16 12:31:38

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.

@blacksun1 2010-07-07 10:09:22

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.

<style type="text/css">
    #i\.Really\.Like\.Cake {
        color: green;
    #i\:Really\:Like\:Cake {
        color: blue;
    <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="//"></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.");

@lstg 2009-04-22 10:18:43

It appears that although colons (:) and periods (.) are valid in the HTML spec, they are invalid as id selectors in CSS so probably best avoided if you intend to use them for that purpose.

@Oriol 2014-11-08 19:52:21

@MathiasBynens The link is broken. Now it's

@Mathias Bynens 2014-11-10 07:09:00

They aren’t invalid if you escape them correctly. See

@Álvaro González 2009-01-10 20:40:31

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)

@pdc 2008-09-16 10:04:28

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.

@Steve Morgan 2008-09-16 09:12:19

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!

@Peter Hilton 2008-09-16 09:09:57

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.

@Mr Shark 2010-11-30 08:33:35

Note that HTML5 allows much more then HTML4 see for example… and

@doc_id 2012-03-03 12:00:54

IE6 didn't support ID starting with underscores, but it's dead anyway.

@Karl 2012-09-13 13:50:46

@rahmanisback regarding IE6, one would have thought so, but I'm finishing up a proposal right now for a bank and they insist that any application a vendor develops runs in IE6. This is for 30,000 users. Heck, if we could just get them to update their browsers on all those desktops, it might just help the unemployment rate.

@doc_id 2012-09-14 06:25:35

@Karl I'm sorry to hear this. Do all of your efforts to warn about IE6 security issues. However IE7 will soon be the new IE6, so yeah it appears to be our fate in this industry to remedy MS past mistakes.

@SWdV 2015-06-14 14:34:25

@MrShark The second link is broken; New link

Related Questions

Sponsored Content

24 Answered Questions

[SOLVED] HTML 5: Is it <br>, <br/>, or <br />?

  • 2009-12-22 13:39:08
  • Eikern
  • 1226366 View
  • 1811 Score
  • 24 Answer
  • Tags:   html html5

26 Answered Questions

[SOLVED] How to change an element's class with JavaScript?

  • 2008-10-12 20:06:43
  • Nathan Smith
  • 2269256 View
  • 2443 Score
  • 26 Answer
  • Tags:   javascript html dom

51 Answered Questions

21 Answered Questions

[SOLVED] How can I set the default value for an HTML <select> element?

  • 2010-08-19 01:10:51
  • Jichao
  • 2036054 View
  • 1154 Score
  • 21 Answer
  • Tags:   html html-select

4 Answered Questions

[SOLVED] What is the purpose of the "role" attribute in HTML?

  • 2012-05-01 10:11:45
  • jeroen
  • 493566 View
  • 1008 Score
  • 4 Answer
  • Tags:   html

9 Answered Questions

[SOLVED] Why does HTML think “chucknorris” is a color?

28 Answered Questions

[SOLVED] How do I give text or an image a transparent background using CSS?

  • 2009-04-30 09:00:02
  • Stijn Sanders
  • 1499014 View
  • 2092 Score
  • 28 Answer
  • Tags:   html css opacity

33 Answered Questions

[SOLVED] Change an HTML5 input's placeholder color with CSS

24 Answered Questions

[SOLVED] Retrieve the position (X,Y) of an HTML element

14 Answered Questions

[SOLVED] How can I select an element by name with jQuery?

Sponsored Content