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.
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.
What am I missing here?
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>
Try this :
document.querySelector("[id='your-id-here-with-special-char']")
should work. let me know
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With