42

Can I have an element that has an id that starts with or is completely numbers?

E.g. something like this:

<div id="12"></div>
Zach Saucier
  • 21,903
  • 12
  • 75
  • 126
jslearner
  • 18,191
  • 17
  • 35
  • 35
  • It may work in some browsers, at least works in IE8 and FF3.5, but as mentioned, start the ID with a letter. http://jsfiddle.net/LncAc/ – amit_g Apr 15 '11 at 06:07
  • 1
    Yes, you can (as of HTML5). Here's a short, complete answer: http://stackoverflow.com/a/31773673/3597276 – Michael Benjamin Aug 02 '15 at 15:58
  • Possible duplicate of [What are valid values for the id attribute in HTML?](http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html) – user May 19 '16 at 17:44

8 Answers8

54

Can I have a div with id as number?

Yes, you can.

id values that consist solely of digits are perfectly valid in HTML; anything but a space is okay. And although earlier HTML specs were more restrictive (ref, ref), requiring a small set of chars and starting with a letter, browsers never cared, which is a big part of why the HTML5 specification opens things up.

If you're going to use those ids with CSS selectors (e.g, style them with CSS, or locate them with querySelector, querySelectorAll, or a library like jQuery that uses CSS selectors), be aware that it can be a pain, because you can't use an id starting with a digit in a CSS id selector literally; you have to escape it. (For instance, #12 is an invalid CSS selector; you have to write it #\31\32.) For that reason, it's simpler to start it with a letter if you're going to use it with CSS selectors.

Those links above in a list for clarity:

Below is an example using a div with the id "12" and doing things with it three ways:

  1. With CSS
  2. With JavaScript via document.getElementById
  3. With JavaScript via document.querySelector (on browsers that support it)

It works on every browser I've ever thrown at it (see list below the code). Live Example:

(function() {
  "use strict";

  document.getElementById("12").style.border = "2px solid black";
  if (document.querySelector) {
    document.querySelector("#\\31\\32").style.fontStyle = "italic";
    display("The font style is set using JavaScript with <code>document.querySelector</code>:");
    display("document.querySelector(\"#\\\\31\\\\32\").style.fontStyle = \"italic\";", "pre");
  } else {
    display("(This browser doesn't support <code>document.querySelector</code>, so we couldn't try that.)");
  }

  function display(msg, tag) {
    var elm = document.createElement(tag || 'p');
    elm.innerHTML = String(msg);
    document.body.appendChild(elm);
  }
})();
#\31\32 {
  background: #0bf;
}
pre {
  border: 1px solid #aaa;
  background: #eee;
}
<div id="12">This div is: <code>&lt;div id="12">...&lt;/div></code>
</div>
<p>In the above:</p>
<p>The background is set using CSS:</p>
<pre>#\31\32 {
    background: #0bf;
}</pre>
<p>(31 is the character code for 1 in hex; 32 is the character code for 2 in hex. You introduce those hex character sequences with the backslash, <a href="http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier">see the CSS spec</a>.)</p>
<p>The border is set from JavaScript using <code>document.getElementById</code>:</p>
<pre>document.getElementById("12").style.border = "2px solid black";</pre>

I've never seen the above fail in a browser. Here's a subset of the browsers I've seen it work in:

  • Chrome 26, 34, 39
  • IE6, IE8, IE9, IE10, IE11
  • Firefox 3.6, 20, 29
  • IE10 (Mobile)
  • Safari iOS 3.1.2, iOS 7
  • Android 2.3.6, 4.2
  • Opera 10.62, 12.15, 20
  • Konquerer 4.7.4

But again: If you're going to use CSS selectors with the element, it's probably best to start it with a letter; selectors like #\31\32 are pretty tricky to read.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • 3
    Just to add - just because you *can* do something does not mean you *should*. It doesn't matter if HTML5 gets rid of the restriction, it's pretty standard amongst programmers not to start methods, functions or anything with numbers - so why change for a markup language? Stick with what you already do :) – Jimbo May 31 '13 at 11:21
  • Just as an aside, and sorry to necro, this is one of my issues with HTML5. For every awesome feature it adds, it screws up the validations and rules we've become so accustomed to in HTML/XHTML, probably a reason why people are having so many issues these days, ya know? – Zarathuztra Dec 09 '13 at 14:26
  • @Zarazthuztra: Apparently in this case, it was just a reflection of reality. It was already the case that browsers allowed anything but a space, so they codified it. – T.J. Crowder Dec 09 '13 at 14:38
  • @T.J.Crowder I agree with you, but with HTML5 adoption so scattered, well, at least when this question was asked, it just caused a bunch of problems for people, know what I mean? Oh well, HTML5 ftw anyway :) – Zarathuztra Dec 09 '13 at 14:43
  • I dont think we are allowed to use div ID, starts with a numerical character ...... http://www.w3.org/TR/html4/types.html#type-name – Hitesh May 12 '14 at 04:31
  • @hitesh: Sure you can. I quoted two HTML specs above in my original answer (both more recent than that one). I've added an example and demo page. You can do it. I'm not saying I think it's a good idea. – T.J. Crowder May 12 '14 at 06:34
  • @T.J Crowder : Thanks for new information, Example is really helpful – Hitesh May 12 '14 at 09:57
  • I don't like how so many people strongly discourage certain valid practices. This may not be practical (and definitely not pretty) if you're using the id for a template-type element, but it's perfectly practical and elegant if you're using element ids for something like comments to allow them to be anchored with #id. And you're 99.9% of the time never going to need a css rule for that. –  Mar 30 '15 at 19:18
  • 1
    @fay: Agreed. **If** you're not going to use CSS selectors with the element, there's no particularly good reason not to have an all-digits `id`. I've rephrased a bit to A) Be more clear, B) Be less didactic. – T.J. Crowder Mar 30 '15 at 21:39
6

From the HTML 5 specs...

The id attribute specifies its element's unique identifier (ID). [DOM]

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.

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 fragment identifiers, as a way to target an element when scripting, and as a way to style a specific element from CSS.

Identifiers are opaque strings. Particular meanings should not be derived from the value of the id attribute.

So... yes :)

From the HTML 4.01 specs...

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

So... no :(

Hristo
  • 42,002
  • 60
  • 155
  • 224
2

From a maintainability standpoint this is a bad idea. ID's should be at least somewhat descriptive of what they represent. Prefix it with something meaningful to be compliant with what others have already answered with. For example:

<div id ="phoneNumber_12" > </div>
Zarathuztra
  • 3,057
  • 1
  • 18
  • 33
  • Downvote care to explain? Sorry, but in no part of this answer is there a mistake. It's an agreement and suggestion based on what others have said. – Zarathuztra Dec 09 '13 at 14:24
  • 2
    I'm not downvoting but would like to make the observation that with large numbers of id's this approach leads to a lot of essentially valueless bloat. Also, it means that every time an id is referenced, it needs to be parsed to split off the phoneNumber_ bit and get at the real id. Also IDs are not intended to have semantic meaning, they are just intended to be unique. – Pancho Apr 07 '16 at 22:13
  • I agree to an extent. It's a readability item that can help. Overall this is a bad idea still. Needs some rethought – Zarathuztra Nov 12 '20 at 20:18
2

You can also select that type of id(though it is definitely not the best practice to create such an id that starts with a number) by doing the following:

document.querySelector('div[id="12"]'); //or 
document.querySelectorAll('div[id="12"]'); //if you have multiple elements with equal ID.
dre.dev
  • 193
  • 1
  • 11
0

While TJ Crowder's answer is conceptually good, it doesn't work for descendant CSS selectors.

Escaping only the first character followed by space does work however (as at Chrome 49)

Assume the following HTML snippet:

<td id="123456">
 <div class="blah">
  <div class="yadah">play that funky music</div>
 </div>
</td>

The following statement:

document.querySelector("#\\31 23456 .blah .yadah").style.fontStyle = "italic";

correctly displays play that funky music

Pancho
  • 1,498
  • 16
  • 33
0

As pointed out in other responses, 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 (".").

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.

As noted in other responses, jQuery has problems with ids that contain periods and colons.

A more subtle problem is that some browsers have been known to mistakenly treat id attribute values as case-sensitive. That means that if you type id="firstName" in your HTML (lower-case 'f') and .FirstName { color: red } in your CSS (upper-case 'F'), a buggy browsers will not set the element's color to red. Because both definitions use valid characters for the id, you will receive no error from a validation tool.

You can avoid these problems 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.

Same Question is Already ask

What are valid values for the id attribute in HTML?

Community
  • 1
  • 1
Anand Thangappan
  • 3,000
  • 2
  • 25
  • 31
  • 1
    *"jQuery has problems with ids that contain periods and colons"* Does it? In a release from the last couple of years? What kind of problems? Any that aren't user errors? Links: [Using IDs with dots and colons in the 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), [example](http://jsbin.com/unodo5) Regardless, though, you nevertheless make a good point about compatibility with imperfect tools. – T.J. Crowder Apr 15 '11 at 08:54
0

No, In experience, it has to start with a letter. You can use numbers if you want after the first character being a letter.

-3

No. It has to start with a letter. See http://www.electrictoolbox.com/valid-characters-html-id-attribute/. You can use numbers after the first character, however, e.g. a1 or theansweris42.

Rafe Kettler
  • 69,672
  • 18
  • 145
  • 147