Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  39] [ 2]  / answers: 1 / hits: 20219  / 5 Years ago, tue, january 7, 2020, 12:00:00

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



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



What am I missing here?


More From » reactjs

 Answers
30

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>




[#51326] Saturday, December 28, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
theron

Total Points: 168
Total Questions: 93
Total Answers: 94

Location: South Georgia
Member since Fri, Nov 13, 2020
4 Years ago
;