Theo
Theo

Reputation: 31

HTML IDs that start with a number

I generate GUIDs for id's in my HTML like

<div id="9121c01e-888c-4250-922f-cf20bcc7d63f">...</div>

According to HTML5 specs, this is valid. However, if you try to find such a element with document.querySelector or document.querySelectorAll, you'll get an error saying that the selector is invalid.

I know that for CSS rules, such an ID is not valid. Does the querySelector methods of 'document' rely on CSS?

Upvotes: 1

Views: 735

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

Does the querySelector methods of 'document' rely on CSS?

The strings you pass querySelector and querySelectorAll are CSS selectors. So yes, they follow the rules of CSS selectors, one of which (as you mentioned) is that an ID selector cannot start with an unescaped digit. So they don't rely on CSS per se, but they follow the syntax of CSS selectors.

You can select that element either by escaping the first digit (which is fairly ugly*):

var e = document.querySelector("#\\39 121c01e-888c-4250-922f-cf20bcc7d63f");

...or by using an attribute selector:

var e = document.querySelector("[id='121c01e-888c-4250-922f-cf20bcc7d63f']");

Example:

document.querySelector("#\\39 121c01e-888c-4250-922f-cf20bcc7d63f").innerHTML = "Yes!";
document.querySelector("[id='9121c01e-888c-4250-922f-cf20bcc7d63f']").style.color = "green";
<div id="9121c01e-888c-4250-922f-cf20bcc7d63f">...</div>

Of course, if you're just getting the element by its ID and not using a compound selector starting with an ID, just use getElementById, which doesn't use a CSS selector, just the ID value as plain text:

var e = document.getElementById("9121c01e-888c-4250-922f-cf20bcc7d63f");

You only need the other form if you're using a compound selector ("#\\39 121c01e-888c-4250-922f-cf20bcc7d63f > span a"), or passing a selector string into something you don't have control over that you know will use querySelector.


* In a CSS selector, \ followed by up to six hex characters (plus a space if you don't use all six) specifies a character code in hex. 0x39 is the character code for the digit 9. And of course, we had to escape the \ in the string literal since otherwise it would have been consumed by the string literal.

Upvotes: 5

MrGoofus
MrGoofus

Reputation: 883

Yes, they use CSS selectors

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

Syntax
element = document.querySelector(selectors);
where

element is an Element object.
selectors is a string containing one or more CSS selectors separated by commas.

But as you append the GUID as ids you can use document.getElementById();

It supports this case.

Upvotes: 0

Related Questions