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?
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?
Share Improve this question edited Jan 8, 2020 at 0:07 CertainPerformance 371k55 gold badges349 silver badges356 bronze badges asked Jan 7, 2020 at 22:53 DohaHelmyDohaHelmy 8091 gold badge8 silver badges20 bronze badges 7- 3 Post your code as text, not images. – Barmar Commented Jan 7, 2020 at 22:55
-
2
Does
document.getElementById(elements[1].id)
work for you? If so, I would hazard a guess that it is erroring on the$
– Taplar Commented Jan 7, 2020 at 22:55 -
Your target ID and actual ID differ, and appear to be randomly-generated. You'll need a different selector, such as the first child of
#itemList
. – Obsidian Age Commented Jan 7, 2020 at 22:56 -
2
$
has special meaning in selectors. Use a different character or escape it with backslashes. – Barmar Commented Jan 7, 2020 at 22:57 -
1
document.querySelector('#' + elements[1].id.replace('$', '\\$') + ' .item')
– Barmar Commented Jan 7, 2020 at 22:58
4 Answers
Reset to default 5Selecting 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
Also try this:
document.getElementById(id)
I've tested on a maximum of 10 randomly generated integers, and NPM uuid (which is like 32 bits of numbers idk it's a lot).
I had the exact same issue after migrating to Angular 13. I solved it by also migrating to Bootstrap 5.