Failed to execute ‘querySelector’ on ‘Document – javascript this keyword

I have the following code in my react component useEffect(() => { document .querySelector(‘#client-list > … Read more Failed to execute ‘querySelector’ on ‘Document – javascript this keyword

I have the following code in my react component

useEffect(() => {
    document
      .querySelector('#client-list > li')
      .addEventListener('click', function (e) {
        e.preventDefault();

        if (document.querySelector(this).index() === 0) {
          document.querySelector('.client-parent').removeClass('hidden');
          document.querySelector('.client-avatar-output').classList.add('mb-2');
        } else {
          document.querySelector('.client-parent').classList.add('hidden');
        }
      });
    }, []);

return (
  <ul id='client-list'>
    <li>Item1</li>
    <li>Item2</li>
  </ul>
)

for this keyword in line document.querySelector(this).index it throws the following error when list item is clicked.

SyntaxError: Failed to execute ‘querySelector’ on ‘Document’: ‘[object
HTMLLIElement]’ is not a valid selector.

what am i doing wrong. any help will be greatly appreciated. thanks

Source: React – Stack Overflow



Leave a Reply

Your email address will not be published. Required fields are marked *