Valid values for the id attribute in HTML elements

This post is a sum up of when creating the id attributes for HTML elements, what rules are there to follow for the value of id?

Valid values for the id attribute in HTML elements

According to HTML4 specifications:

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.

But a variety of browsers, CSS editors, and JavaScript frameworks apply some restrictions above the definition. So the valid values for the id attribute in HTML  elements has some limitation. We can note them as follow:

  • Some browsers treat id attribute values as case-sensitive while other browsers do not. which is a subtle problem. As an example if you assign id="nameGreen" in your HTML element (lower case ‘n‘) and #NameGreen { color: green; }   in your CSS (upper case ‘N‘) then a buggy browser will will set the element’s color to green.  Because both definitions use valid characters for the id, you will receive no error from a validation tool.
  • jQuery has problems with ids that contain periods and colons.
  • Note that class and id attributes are case-sensitive in XHTML, all other attributes are not.
  • Id beginning with a number won’t work with a CSS rule to target element by id.

So you can technically use colons and periods in id/name attributes, but I would strongly suggest avoiding both. And you can avoid these problems by strictly sticking to a naming convention, limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick only one and never use the other), then you have an easy-to-remember pattern. You will never wonder “was it nameGreen or NameGreen?” because you will always know that you should type name-green.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.