Toggle class to an element by click another element

前端 未结 5 2048
暗喜
暗喜 2021-01-16 09:52

I want to click on an element to toggle a class being referenced on a completely unrelated element (not a child, parent or sibling)

For example, initially the code w

5条回答
  •  猫巷女王i
    2021-01-16 10:15

    Multiple elements with class navigation

    navigation is a class, so I assume there is more than one element you would like to give class open on click on element with id button. Do it that way:

    function toggleNavigation(element) {
      element.classList.toggle('open');
    }
    
    document.getElementById('button').addEventListener('click', function() {
      Array.from(document.getElementsByClassName('navigation')).forEach(toggleNavigation);
    });
    .navigation {
      background-color: lightgreen;
    }
    .navigation.open {
      background-color: lightblue;
    }
    Button
    
    
    
    

    Single element with class or id navigation

    If it is otherwise (i.e., there is only one element with class navigation, in which case it should be an id, not a class) you can replace above JavaScript to:

    document.getElementById('button').addEventListener('click', function() {
      document.getElementsByClassName('navigation')[0].classList.toggle('open');
    });
    

    or if you will change navigation to be an id:

    document.getElementById('button').addEventListener('click', function() {
      document.getElementById('navigation').classList.toggle('open');
    });
    

提交回复
热议问题