Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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

share|improve this question
50  
This differs between HTML5 and previous versions of the spec. I explained it here: mathiasbynens.be/notes/html5-id-class – Mathias Bynens Oct 24 '11 at 8:41
3  
I noticed SharePoint 2010 assigning a value like this - {8CC7EF38-31D8-4786-8C20-7E6D56E49AE2}-{E60CE5E2-6E64-4350-A884-654B72DA5A53} for a dynamically generated table within a Web Part & a page containing an ID value of that sort did not break in any of the popular browsers. Dealing with such ID values through JavaScript is tricky though - mvark.blogspot.in/2012/07/… – mvark Jul 20 '12 at 18:34
    
HTML4 and HTML5 requirements for ID values are very different. Here's a quick and complete rundown of HTML5 ID rules: stackoverflow.com/a/31773673/3597276 – Michael_B Aug 3 '15 at 0:32
    
Please note: Doing as some of the answers have said and using a period (**.**) with jQuery will run you into quite a bit of trouble, for example, using <input id="me.name" /> and then $("#me.name").val() will cause jQuery to look for a <me> tag with the class .name, which no one wants really! – Sam Swift 웃 Aug 26 '15 at 15:20

20 Answers 20

up vote 981 down vote accepted

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 [citation needed].

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.

share|improve this answer
59  
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. – John Topley Apr 22 '09 at 10:35
17  
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! – Zack The Human Jan 20 '10 at 0:53
42  
As for '.' or ':' in an ID using jQuery, see the jQuery FAQ. It contains a small function that does the necessary escaping. – Wolfram May 6 '10 at 10:18
7  
Note that HTML5 allows much more then HTML4, see for example 456bereastreet.com/archive/201011/… and w3.org/TR/html5/elements.html#the-id-attribute – Mr Shark Nov 30 '10 at 8:36
5  
The id attribute is [w3.org/TR/html4/struct/global.html#adef-id](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. – Augustus Kling Sep 30 '11 at 7:55

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.

share|improve this answer
13  
Note that HTML5 allows much more then HTML4 see for example 456bereastreet.com/archive/201011/… and w3.org/TR/html5/elements.html#the-id-attribute – Mr Shark Nov 30 '10 at 8:33
    
IE6 didn't support ID starting with underscores, but it's dead anyway. – rahmanisback Mar 3 '12 at 12:00
1  
@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. – Karl Sep 13 '12 at 13:50
1  
@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. – rahmanisback Sep 14 '12 at 6:25
    
@MrShark The second link is broken; New link – SWdV Jun 14 '15 at 14:34

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.

share|improve this answer
11  
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(/\:/,’\\:’)) groups.google.com/group/jquery-en/browse_thread/thread/… – joeformd Dec 3 '09 at 10:41
    
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. – cori May 2 '11 at 16:35
3  
Just FYI, dashes are technically hyphens. Minus sign isn't in ASCII character set. en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes – Anton Strogonoff Jul 8 '11 at 18:31
    
@jowformd: interesting idea using replace in the selector, instead of using the function twice, why not just improve the regex id.replace(/([\.:])/g,"\\$1") – vol7ron Oct 18 '11 at 16:57
1  
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='my.cool:thing'], however this selector will have a lower specificity than an id selector, which might cause other problems. – Faust Jun 7 '13 at 7:36

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)

share|improve this answer

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.

share|improve this answer
1  
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"). – foo Jan 7 '11 at 5:09
    
Yepp, updated the pattern. – Mr Shark Jan 12 '11 at 9:26

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.

share|improve this answer

HTML5:

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.

PRE-HTML5:

ID should match:

[A-Za-z][-A-Za-z0-9_:.]*
  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.

share|improve this answer

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>
share|improve this answer

HTML5

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)
share|improve this answer

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>

CSS

#maintenance\.instrumentNumber{word-wrap:break-word;}
share|improve this answer
2  
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). – w3dk Nov 14 '13 at 1:25

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!

share|improve this answer
15  
So why not to delete this answer... there are so many to be read!.. O_o" – bluish Mar 15 '11 at 9:18

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.

share|improve this answer
    
@MathiasBynens The link is broken. Now it's mothereff.in/css-escapes#0foo%23bar.baz%3Aqux – Oriol Nov 8 '14 at 19:52
    
They aren’t invalid if you escape them correctly. See mothereff.in/css-escapes#0foo%23bar.baz%3Aqux – Mathias Bynens Nov 10 '14 at 7:09

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.

share|improve this answer

HTML5 ID Attribute Values

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 punctuation and special characters in the value of an id may cause trouble in other contexts (e.g., CSS, JavaScript, regex). So make sure to escape all characters in other code where they may have special meaning.

share|improve this answer
  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>.
share|improve this answer

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.

share|improve this answer

Older versions of Netscape had problems with _ in names/elements, so I've stuck to A-Z, a-z, 0-9 and "-" in my IDs out of habit. I'd stretch to _:s, but I haven't had any real reason to use them. Shrugs

share|improve this answer

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.

share|improve this answer

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

share|improve this answer
5  
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." – Andrew Barber Sep 16 '14 at 19:22

You can use big and small english alphabet letters (A-Z & a-z), numbers (0-9), you can't start with numbers, no space, everything else is not allowed.

share|improve this answer

protected by Bill the Lizard Sep 12 '12 at 12:43

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.