Difference between getElementByID and querySelector
Assume you have a valid HTML element in DOM. I assumed the following snippets to be the same.
let id = "037e3778-e157-4715-bff5-e466230fe7a3"
const byId = document.getElementById(id)
console.log(byId) // works
const bySelectorConcat = document.querySelector("#" + id)
console.log(bySelectorConcat) // Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#037e3778-e157-4715-bff5-e466230fe7a3' is not a valid selector.
const bySelector = document.querySelector(`#${id}`)
console.log(bySelector) // Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#037e3778-e157-4715-bff5-e466230fe7a3' is not a valid selector.
Turns out that IDs with leading numbers are valid HTML selector, but not valid CSS selectors.
These are some improved versions:
let id = "037e3778-e157-4715-bff5-e466230fe7a3"
const querySelectorFixed = document.querySelector(`[id='${id}']`)
console.log(querySelectorFixed)
// better approach
const querySelectorEscaped = document.querySelector(`#${CSS.escape(id)}`)
console.log(querySelectorEscaped)
PS: I write a Newsletter, feel free to subscribe or follow me on Twitter.