'TypeScript with React - TS Error Looping through LI elements

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?



Solution 1:[1]

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>
  ))
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance