Reputation: 3068
Looping through a collection of <li>
elements to remove a specific class, before re-adding the same class to a different <li>
. Here is the code:
useEffect(() => {
if (dnArrowIdx === undefined) {
const allLi = Array.from(document.querySelectorAll('#srxResultsDiv ul li'));
const dLi = document.querySelector(`#srxResultsDiv ul li:nth-child(${dnArrowIdx})`);
if (allLi !== null) {
allLi.forEach((li) => {
li.removeClass('liHoverBg');
});
}
if (dLi !== null) dLi.classList.add('liHoverBg');
}
}, [dnArrowIdx]);
The removeClass
on line li.removeClass('liHoverBg')
is underlined in red. Error message is:
Property 'removeClass' does not exist on type 'Element'.ts(2339)
How would I solve this?
Upvotes: 0
Views: 741
Reputation: 371233
removeClass
exists in jQuery, but not in JS. To do this in JS, use classList.remove
:
li.classList.remove('liHoverBg');
But this is still a very odd thing to do in React. Instead of selecting elements and manipulating them through DOM methods, you should render the elements via React and have React either return the element with a liHoverBg
class or not, eg, something like:
{
results.map((resultText, i) => (
<li
className={i === dnArrowIdx + 1 ? 'liHoverBg' : ''}
>{resultText}</li>
))
}
Upvotes: 5