Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '' is not a valid selector

I have a list with two items. The second item's ID is generated by getTime() and concatenated with new$, forming a random ID as shown in the image below.

enter image description here

I need to target that element to perform some functions, but when I try to do that using querySelector, it produces an error saying that it is not a valid selector, even when I use String() to covert the generated random number to a string.

enter image description here

What am I missing here?

like image 778
DohaHelmy Avatar asked Sep 02 '25 02:09

DohaHelmy


2 Answers

Selecting elements with a particular ID using the # syntax doesn't allow for an unescaped $s inside the ID. You could bypass this by selecting the parent element via [id="<some id>"] instead:

console.log(
  document.querySelector('[id="foo$bar"] .item')
);
<div id="foo$bar">
  <div class="item">
    item
  </div>
</div>

Or escape the $ with a backslash first:

const idSelector = 'foo$bar'.replace(/\$/g, '\\$');
console.log(
  document.querySelector('#' + idSelector + ' .item')
);
<div id="foo$bar">
  <div class="item">
    item
  </div>
</div>
like image 80
CertainPerformance Avatar answered Sep 04 '25 15:09

CertainPerformance


Try this :

document.querySelector("[id='your-id-here-with-special-char']")

should work. let me know

like image 21
rivelbab Avatar answered Sep 04 '25 15:09

rivelbab