-1

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.

voo94083
  • 29
  • 1
  • 4
  • 1
    HTML IDs aren't allowed to start with numbers. See https://css-tricks.com/ids-cannot-start-with-a-number/ – code Jan 15 '23 at 01:34
  • Thanks for the reply! I understand how to work around an ID that starts w/ a number in CSS, but I'm still a little lost with exactly how to work with an ID that starts w/ a number when passing it into document.querySelector(). I tried to escape the number using: const msgExists = document.querySelector(\`#${msg._id}\`); which doesn't seem to work. Then I tried const msgExists = document.querySelector([id=\`${msg._id}`]); AND const msgExists = document.querySelector('#' + [id=\`${msg._id}\`]); which both do not seem to work... – voo94083 Jan 15 '23 at 01:58

1 Answers1

1

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/>
ksav
  • 20,015
  • 6
  • 46
  • 66