Search code examples
javascriptdomgetelementbyidqueryselector

document.querySelector() w/ integers --- DOMException: Failed to execute 'querySelector' on 'Document' ... is not a valid selector


I'm running into some conflicting information with regards to how to use document.querySelector() when passing in a variable which happens to be an integer.

In my code I'm trying to check if a particular HTML element exists on the page or not. I'm doing this by utilizing document.querySelector and passing in the ID of that element which happens to be a number. Because I'm selecting for an ID I am also passing in the '#' and therefore am using a template literal because the ID is stored inside of a variable.

Let's say: msg._id = 63c347f214f8baf0457355d3

//this works

const msgExists = document.getElementById(msg._id);

//this doesn't

const msgExists = document.querySelector(`#${msg._id}`);

and produces the following error message:

55index.js:23 Error in fetching messages DOMException: Failed to execute 'querySelector' on 'Document': '#63c347f214f8baf0457355d3' is not a valid selector. at http://localhost:3434/js/index.js:35:34 at Array.forEach () at postMessages (http://localhost:3434/js/index.js:29:10) at http://localhost:3434/js/index.js:20:9 at async fetchMessages (http://localhost:3434/js/index.js:16:5)

I've also tried using string concatenation instead of a template literal.

/this also does not work

const msgExists = document.querySelector('#' + msg._id);`

and produces the same error as above.

I've found the solution which is to use document.getElementById instead, but would like to know why document.querySelector is not working when I'm trying to pass in a variable which is a number? I think it has something to do with escaping characters, but I'm not exactly sure what needs to be escaped.


Solution

  • You can workaround the issue by using an attribute selector

    // error
    // const msgExists = document.querySelector('#63c347f214f8baf0457355d3')
    
    // no error
    const msgExists = document.querySelector("[id='63c347f214f8baf0457355d3']")
    
    console.log(msgExists)
    <p id="63c347f214f8baf0457355d3">test<p/>