O
O
Oleg Morev2018-03-07 15:34:54
JavaScript
Oleg Morev, 2018-03-07 15:34:54

How to remove the class from all neighboring elements?

Good afternoon, please tell me how to remove the selected class on click, for an inactive item)
https://fiddle.jshell.net/9Lufhat3/163/
PS JQ do not offer, about .siblings() in the know :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-03-07
@DpOLEGapx

Delegate click handling to the container.
When clicking, you can search for an element with the desired class, remove the class, set the class to the clicked one. Like like this :

document.querySelector('nav').addEventListener('click', function(e) {
  if (e.target.classList.contains('sidebar-item')) {
    const selected = this.querySelector('.selected');
    if (selected) {
      selected.classList.remove('selected');
    }

    e.target.classList.add('selected');
  }
});

Or you can iterate over all elements, switching the class depending on whether the current element is clicked. Something like this :
document.querySelector('nav').addEventListener('click', function({ target: t }) {
  if (t.classList.contains('sidebar-item')) {
    this.querySelectorAll('.sidebar-item').forEach(n => n.classList.toggle('selected', n === t));
  }
});

A
Anton fon Faust, 2018-03-07
@bubandos

Like this: https://fiddle.jshell.net/anton4ept/3gsgyxon/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question