2116

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

Cleptus
  • 2,738
  • 4
  • 26
  • 28
Mr Shark
  • 24,254
  • 5
  • 29
  • 36
  • 103
    This differs between HTML5 and previous versions of the spec. I explained it here: http://mathiasbynens.be/notes/html5-id-class – Mathias Bynens Oct 24 '11 at 08:41
  • 5
    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 - http://mvark.blogspot.in/2012/07/building-dynamic-jquery-selector-for.html – mvark Jul 20 '12 at 18:34
  • 3
    HTML4 and HTML5 requirements for `ID` values are very different. Here's a quick and complete rundown of HTML5 `ID` rules: http://stackoverflow.com/a/31773673/3597276 – Michael Benjamin Aug 03 '15 at 00:32
  • 6
    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 `` and then `$("#me.name").val()` will cause jQuery to look for a `` tag with the class `.name`, which no one wants really! – Can O' Spam Aug 26 '15 at 15:20
  • 3
    @SamSwift웃 Nope, you just have to escape special characters as [docs say](https://api.jquery.com/category/selectors/). Please check this [online demo](http://jsbin.com/munowivitu/1/edit?html,css,js,console,output). – Álvaro González Nov 10 '16 at 09:58
  • 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): `
    ...` using a jQuery statement like this: `$([id='Usr_order #'])`
    – bkwdesign Feb 24 '17 at 14:04
  • 1
    @mvark GUIDs are hot, but i found that using base64 encoded GUIDs are even hotter. `0dea65ca-eac3-489a-944c-0c522b609f78` is compactly represented as `ymXqDcPqmkiUTAxSK2CfeA`. – Dmitry Jun 16 '18 at 16:46

26 Answers26

1772

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.

Community
  • 1
  • 1
dgvid
  • 24,815
  • 4
  • 37
  • 56
  • 80
    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
  • 34
    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 00:53
  • 56
    As for '.' or ':' in an ID using jQuery, see the jQuery [FAQ](http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_element_by_an_ID_that_has_characters_used_in_CSS_notation.3F). It contains a small function that does the necessary escaping. – Wolfram May 06 '10 at 10:18
  • 7
    The `id` attribute is [http://www.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 07:55
  • 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! – dgvid Sep 30 '11 at 13:36
  • 5
    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. – Stephen Booher Jan 26 '12 at 17:15
  • 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 Mar 21 '12 at 14:43
  • 3
    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 Mar 21 '12 at 14:47
  • 1
    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 Mar 21 '12 at 14:49
  • 1
    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 Mar 21 '12 at 16:24
  • 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 Mar 21 '12 at 16:27
  • 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 Mar 21 '12 at 16:28
  • 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 Mar 21 '12 at 16:33
  • Note that you may also use character references in an ID: "A" is as valid as "A". Note also that *all* chracters in supplementary planes except PUA planes are valid. This also means that the id '􏿿' 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 Mar 21 '12 at 16:38
  • 1
    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 Mar 21 '12 at 16:52
  • 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 Mar 21 '12 at 16:54
  • 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 day!" is perfectly valid in HTML5, but would be invalid in XHTML due to the non-breaking space and the quotes... – verdy_p Mar 21 '12 at 17:19
  • 1
    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: http://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-element-by-an-id-that-has-characters-used-in-css-notation/ and here is the function `function jq( myid ) {return "#" + myid.replace( /(:|\.|\[|\])/g, "\\$1" );}` – Buttle Butkus Nov 14 '14 at 23:12
  • 3
    Is there any length limit? – Tomáš Zato - Reinstate Monica Dec 01 '14 at 22:43
  • @dgvid, will browser throw error if syntax for id attribute breached ? – Kira Jan 08 '15 at 11:07
  • 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. – dgvid Jan 08 '15 at 20:00
  • 1
    *"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 `id`s (you just have to escape them correctly, which is defined in CSS). What "problems" are you talking about? – T.J. Crowder Mar 30 '15 at 21:49
  • 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). – thdoan Apr 27 '15 at 03:31
  • I prefer `first-name`. – Oliver Ni Aug 12 '17 at 09:33
  • 1
    just from a convenience's point of view, you can select the text of `first_name` with double-click, but not `first-name` – XoXo Feb 07 '18 at 15:06
  • @10basetom You can always escape the first character: `\33 d`. – Mr Lister Feb 26 '18 at 14:26
  • 1
    The phrase "you will have to escape those characters using a backslash in CSS or a double backslash in a selector string passed to jQuery" looks confusing. At first I thought that jquery really requires double-slash, but actually it is always a single slash. Double-slash in JS string is required just because in JS strings a slash is escape character also, so to create a css selector from JS string, it is required to escape JS slash to get one slash for CSS selector. `console.log('\\#')` really prints `\#`. – Ruslan Stelmachenko Jun 18 '19 at 21:28
227

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.

Peter Hilton
  • 16,728
  • 6
  • 46
  • 75
  • 21
    Note that HTML5 allows much more then HTML4 see for example http://www.456bereastreet.com/archive/201011/html5_allows_almost_any_value_for_the_id_attribute_use_wisely/ and http://www.w3.org/TR/html5/elements.html#the-id-attribute – Mr Shark Nov 30 '10 at 08:33
  • IE6 didn't support ID starting with underscores, but it's dead anyway. – doc_id Mar 03 '12 at 12:00
  • 2
    @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
  • 2
    @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. – doc_id Sep 14 '12 at 06:25
  • @MrShark The second link is broken; [New link](http://www.w3.org/TR/html-markup/global-attributes.html#common.attrs.id) – SWdV Jun 14 '15 at 14:34
164

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.

Michael Thompson
  • 3,771
  • 1
  • 27
  • 22
  • 24
    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(/\:/,’\\:’)) http://groups.google.com/group/jquery-en/browse_thread/thread/ba072168939b245a – joeformd Dec 03 '09 at 10:41
  • 2
    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 02 '11 at 16:35
  • 7
    Just FYI, dashes *are* technically hyphens. Minus sign isn't in ASCII character set. http://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes – Anton Strogonoff Jul 08 '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
  • 4
    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 07 '13 at 07:36
  • 2
    Old, I know, but updated to include numbers and backpedal on hyphens – Michael Thompson Dec 30 '13 at 15:03
69

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)

Álvaro González
  • 128,942
  • 37
  • 233
  • 325
67

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.

nasmorn
  • 2,100
  • 1
  • 18
  • 28
Mr Shark
  • 24,254
  • 5
  • 29
  • 36
63

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.

Community
  • 1
  • 1
Zaheer Ahmed
  • 26,435
  • 11
  • 70
  • 105
61

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.

Michael Benjamin
  • 265,915
  • 79
  • 461
  • 583
33

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.

pdc
  • 2,208
  • 20
  • 27
32

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>
blacksun1
  • 329
  • 3
  • 2
25

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)
Sergio
  • 27,160
  • 10
  • 79
  • 126
18

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;}
Anthony
  • 2,062
  • 6
  • 34
  • 60
  • 3
    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`). – MrWhite Nov 14 '13 at 01:25
16

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!

Steve Morgan
  • 12,638
  • 2
  • 38
  • 49
16

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.

pimvdb
  • 141,012
  • 68
  • 291
  • 345
Vordreller
  • 2,458
  • 9
  • 34
  • 50
12

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.

The_Lone_Devil
  • 496
  • 11
  • 15
Bhavin Solanki
  • 1,296
  • 11
  • 27
11

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.

lstg
  • 127
  • 1
  • 4
10

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.

Kanishka Panamaldeniya
  • 16,046
  • 27
  • 109
  • 185
9
  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>.
  • "underscore can also use but not good for seo": Since when did search engines take any interest in CSS class or id names? – Nick Rice May 07 '16 at 16:55
9

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

Tazwar Utshas
  • 771
  • 1
  • 14
  • 26
6

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

Joel Wembo
  • 705
  • 5
  • 8
5

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

it is use for HTML5 ...

we can add id with any tag.

4

In HTML

ID should start with {A-Z} or {a-z} you can Add Digits, period, hyphen, underscore, 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 ID as Selector. Mainly when you want to Use Pseudo elements (:before,:after).

Also in JS it is Hard to select these ID's. So you should use first four ID's As preferred by many developer around and if it's necessary than you can use last two also.

Dev pokhariya
  • 144
  • 2
  • 12
2

Since ES2015 we can as well use -almost- all unicode characters for ID's, if the document charset is set to UTF8.

Test out here: https://mothereff.in/js-variables

enter image description here

Read about: https://mathiasbynens.be/notes/javascript-identifiers-es6

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(
   target
)
document.getElementById(target).style.backgroundColor = "black"
div {
  border: 1px black solid;
  width: 100%;
  height: 200px
}
<div id="H̹̙̦̮͉̩̗̗ͧ̇̏̊̾Eͨ͆͒̆ͮ̃͏̷̮̣̫̤̣Cͯ̂͐͏̨̛͔̦̟͈̻O̜͎͍͙͚̬̝̣̽ͮ͐͗̀ͤ̍̀͢M̴̡̲̭͍͇̼̟̯̦̉̒͠Ḛ̛̙̞̪̗ͥͤͩ̾͑̔͐ͅṮ̴̷̷̗̼͍̿̿̓̽͐H̙̙̔̄͜">

Should you use it? Probably not a good idea!

Read about: https://stackoverflow.com/a/52799593/2494754

NVRM
  • 6,477
  • 1
  • 51
  • 60
0

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 );
</script>
Danny '365CSI' Engelman
  • 6,903
  • 1
  • 16
  • 29
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.

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

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.