HTML: Valid id attribute values?
Asked Answered
G

27

2289

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

Glacis answered 16/9, 2008 at 9:8 Comment(7)
This differs between HTML5 and previous versions of the spec. I explained it here: mathiasbynens.be/notes/html5-id-classChrysa
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/…Largely
HTML4 and HTML5 requirements for ID values are very different. Here's a quick and complete rundown of HTML5 ID rules: https://mcmap.net/q/17639/-html-valid-id-attribute-valuesArsis
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!Jaye
@SamSwift웃 Nope, you just have to escape special characters as docs say. Please check this online demo.Slavophile
I know the OP is asking about generating valid IDs (and not how to jQuery an existing DOM), but, @Faust's comment way below will be so useful to others who may've googled into this the same way I did. Using his technique: I was able to successfully query for elements like this one (featuring a space): <div id="Usr_order #">... using a jQuery statement like this: $([id='Usr_order #'])Transpierce
@Largely GUIDs are hot, but i found that using base64 encoded GUIDs are even hotter. 0dea65ca-eac3-489a-944c-0c522b609f78 is compactly represented as ymXqDcPqmkiUTAxSK2CfeA.Albano
M
1891

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.

Mccorkle answered 17/9, 2008 at 1:42 Comment(6)
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.Estebanesteem
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!Barbabas
As for '.' or ':' in an ID using jQuery, see the jQuery FAQ. It contains a small function that does the necessary escaping.Lei
The jquery FAQ answer that @Lei references is how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation.Ronaldronalda
another crucial constraint on the id value is that it must be unique. I know this may seem obvious, but I've seen this rule broken far too many timesGiarla
I had a problem with Firefox not being able to apply a CSS using span#hs.order. See also bugzilla.mozilla.org/show_bug.cgi?id=1861666Karajan
I
240

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.

Intransitive answered 16/9, 2008 at 9:9 Comment(1)
Note that HTML5 allows much more then HTML4 see for example 456bereastreet.com/archive/201011/… and w3.org/TR/html5/elements.html#the-id-attributeGlacis
M
177

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.

Malformation answered 16/9, 2008 at 14:1 Comment(3)
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/…Sacellum
See Álvaro González's answer.Violante
Stick to a-z0-9_-. Avoid upper case also because browsers apparently don't really distinguish between cases (ug).Fishtail
A
81

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

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.

Arsis answered 2/8, 2015 at 15:53 Comment(0)
K
73

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)

Karlotte answered 10/1, 2009 at 20:40 Comment(2)
This is commentary on another answer, and does not attempt to answer the original question.Trumpet
@Trumpet Back in the day, the question was tagged as jQuery. Indeed, it makes little sense now. But, to be honest, I can't remember what I had in mind 13 years ago.Slavophile
G
70

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.

Glacis answered 16/9, 2008 at 9:11 Comment(3)
Or alternatively: "so it might be better to avoid jquery". ;)Joggle
See Álvaro González's answer.Violante
@Joggle Why should we avoid JQuery? Could you please, give us more info?Chorea
L
68

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:

  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 . 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.

Ladder answered 18/1, 2013 at 7:9 Comment(2)
In HTML5, id doesn't accept id="c365720c"Mandolin
Actually HTML5 does.Periphrastic
E
36

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>
Exploiter answered 7/7, 2010 at 10:9 Comment(0)
P
35

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.

Pursuivant answered 16/9, 2008 at 10:4 Comment(0)
T
33

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)
Tijerina answered 26/8, 2013 at 21:54 Comment(0)
F
21

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;}
Fernand answered 13/11, 2013 at 20:14 Comment(1)
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).Paoting
D
19

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 (".").

Delogu answered 16/9, 2008 at 9:12 Comment(0)
K
17

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.

Kibbutz answered 16/9, 2008 at 12:31 Comment(0)
O
13

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+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.

Oz answered 15/7, 2016 at 13:2 Comment(0)
W
12

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.

Witenagemot answered 22/4, 2009 at 10:18 Comment(2)
@MathiasBynens The link is broken. Now it's mothereff.in/css-escapes#0foo%23bar.baz%3AquxHumo
They aren’t invalid if you escape them correctly. See mothereff.in/css-escapes#0foo%23bar.baz%3AquxChrysa
E
11

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.

Epigene answered 21/8, 2013 at 10:57 Comment(2)
Can you add the reference for the quote to your answer? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.)Violante
In HTML5, I create elements with URL as ID which can be targeted by adding the referral URL as the document URL's hash, and browser automatically focuses on the said element upon page load.Periphrastic
T
11

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

Trenna answered 12/11, 2016 at 13:52 Comment(1)
But not required in HTML5? See previous answers.Violante
B
10
  1. IDs are best suited for naming parts of your layout, so you should not give the same name for ID and class
  2. ID allows alphanumeric and special characters
  3. but avoid using the # : . * ! symbols
  4. spaces are not allowed
  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 be used, but it is 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>.
Bellabelladonna answered 2/5, 2013 at 6:28 Comment(1)
"underscore can also use but not good for seo": Since when did search engines take any interest in CSS class or id names?Hyperbole
S
10

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

Enter image description here

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"

Selvage answered 7/9, 2019 at 21:36 Comment(1)
Is there a way to iterate valid identifiers?Aspergillosis
T
8

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

Thorma answered 9/5, 2017 at 4:22 Comment(0)
C
7

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.

Chine answered 14/6, 2019 at 11:23 Comment(0)
P
6

Walues can be: [a-z], [A-Z], [0-9], [* _ : -]

It is used for HTML5...

We can add id with any tag.

Pamella answered 7/7, 2019 at 8:21 Comment(0)
B
2

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.

Biliary answered 11/3, 2021 at 19:13 Comment(0)
H
0

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.

Hemialgia answered 16/9, 2008 at 9:9 Comment(0)
T
0
  1. Uppercase and lowercase alphabets works
  2. '_' and '-' works, too
  3. Numbers works
  4. Colons (,) and period (.) seems to work
  5. Interestingly, emojis work
Terrarium answered 4/4, 2021 at 0:36 Comment(0)
D
0

There are several rules to creating id attributes for HTML elements.

  1. The id attribute must be unique. (No two elements should have the same id value)
    Example:-

    <h1 id="one">Heading One</h1>
    <h1 id="two">Heading Two</h1>

  2. The id attribute must start with **a letter, underscore(_), or hyphen(-)
    Example:-

    <li id="one">One</li>
    <li id="_two">Two</li>
    <li id="-three">Three</li>

  3. The id attribute cannot contain spaces or any other special characters.
    Example:-

    <li id="one@one">One</li>
    <li id="two%two">Two</li>
    <li id="three#three">Three</li>
    <li id="four&four">Three</li>
    <li id="five five">Three</li>

  4. The id attribute should be meaningful and should not be too long or too short.

  5. The good practice to use lowercase letters in the id attribute values.

Disgruntle answered 29/4, 2023 at 2:8 Comment(0)
L
-6

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.

Lilley answered 22/9, 2012 at 18:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.