Skip to content

classList.remove is not working as it should?

I have an issue with this conditional, the goal is to show the li with desc when focusing on it. When another is focused in the domem the previously focused one should be removed.

In other words: Once one desc is showing the the other must disappear, what is strange is that it works for 2 times ok, then it stops doing what it should be doing. I suspect that it might have something to do with the listener, I have to use foucusin thought.

Maybe someone will be able to see where the issue could be:

let parent = document.body
  parent.addEventListener('focusin', function (e) {
        let link = e.target
        if (document.querySelector('.selected')) {
        let suspect = document.querySelector('.selected');
        suspect.classList.remove('.selected');
        suspect.style.display = 'none';
        }
        let checker = link.parentElement.querySelector('.desc');
        checker.classList.add('selected');
        checker.style.display = 'flex';
  })
ul {
  width: 40px;
  background-color: coral;
  border-radius: 5px;
  list-style: none;
}
<ul> 
  <li class='item' contenteditable=true>1<li>
  <li class='desc' style="display: none;">B<li>
</ul>

<ul> 
  <li class='item' contenteditable=true>2<li>
  <li class='desc' style="display: none;">B<li>
<ul>

Answer

I simply removed the . before selected, this was making the querySelector look for the wrong value ( .selected instead of simply selected ).

The fixed snippet can be tested below, hopefully that helps you:

let parent = document.body
  parent.addEventListener('focusin', function (e) {
        let link = e.target
        if (document.querySelector('.selected')) {
        let suspect = document.querySelector('.selected');
        suspect.classList.remove('selected');
        suspect.style.display = 'none';
        }
        let checker = link.parentElement.querySelector('.desc');
        checker.classList.add('selected');
        checker.style.display = 'flex';
  })
ul {
width: 40px;
background-color: coral;
  border-radius: 5px;
  list-style: none;
}
<ul> 
<li class='item' contenteditable=true>1<li>
<li class='desc' style="display: none;">B<li>
</ul>

<ul> 
<li class='item' contenteditable=true>2<li>
<li class='desc' style="display: none;">B<li>
<ul>