Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using querySelector with IDs that are numbers

From what I understand the HTML5 spec lets you use IDs that are numbers like this.

<div id="1"></div>
<div id="2"></div>

I can access these fine using getElementById but not with querySelector. If I try do the following I get SyntaxError: DOM Exception 12 in the console.

document.querySelector("#1")

I'm just curious why using numbers as IDs does not work querySelector when the HTML5 spec says these are valid. I tried multiple browsers.

like image 546
Berry Blue Avatar asked Oct 13 '22 18:10

Berry Blue


People also ask

Can I use querySelector with ID?

From what I understand the HTML5 spec lets you use IDs that are numbers like this. I can access these fine using getElementById but not with querySelector .

How do I select multiple IDs in querySelector?

Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.

How do I find my querySelector ID?

querySelector() method to get an element by id by partially matching a string, e.g. const el = document. querySelector('[id*="my-partial-id"]') . The method returns the first element within the document that matches the provided selector. Here is the HTML for the examples in this article.


1 Answers

It is valid, but requires some special handling. From here: http://mathiasbynens.be/notes/css-escapes

Leading digits

If the first character of an identifier is numeric, you’ll need to escape it based on its Unicode code point. For example, the code point for the character 1 is U+0031, so you would escape it as \000031 or \31 .

Basically, to escape any numeric character, just prefix it with \3 and append a space character ( ). Yay Unicode!

So your code would end up as (CSS first, JS second):

#\31  {
    background: hotpink;
}

document.getElementById('1');
document.querySelector('#\\31 ');
like image 140
Dennis Avatar answered Oct 23 '22 16:10

Dennis