Given
const div = document.createElement("div");
div.id = 111;
document.body.appendChild(div);
try {
console.log(document.querySelector("#111"));
} catch(e) {
console.error(e);
/*
Chromium:
DOMException: Failed to execute 'querySelector' on 'Document':
'#111' is not a valid selector.
Firefox
SyntaxError: '#111' is not a valid selector
*/
}
try {
console.log(document.querySelectorAll("#111"));
} catch(e) {
console.error(e);
/*
Chromium:
DOMException: Failed to execute 'querySelector' on 'Document':
'#111' is not a valid selector.
Firefox
SyntaxError: '#111' is not a valid selector
*/
}
however, document.getElementById()
returns the element
const div = document.createElement("div");
div.id = 111;
document.body.appendChild(div);
try {
console.log(document.getElementById("111"));
} catch(e) {
console.error(e);
}
References:
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 (".").
7.5.2 Element identifiers: the id and class attributes
Attribute definitions
id = name [CS] This attribute assigns a name to an element. This name must be unique in a document.
While this specification defines requirements for class, id, and slot attributes on any element, it makes no claims as to whether using them is conforming or not.
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.
Throws a SYNTAX_ERR exception if the specified group of selectors is invalid.
Throws a SYNTAX_ERR exception if the specified group of selectors is invalid.
Is "111"
a valid HTML id attribute or are document.querySelector()
and document.querySelectorAll()
correctly throwing syntax errors?