Toggle class to an element by click another element

前端 未结 5 2004
暗喜
暗喜 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条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-16 10:03

    You could attach click event to the button with id button then on click select the element with class navigation using getElementsByClassName() (ti will return list of nodes) then select the first one using [0] then use toggle() :

    document.getElementById('button').onclick = function(){
         document.getElementsByClassName('navigation')[0].classList.toggle("open");
    } 
    

    Hope this helps.


    document.getElementById('button').onclick = function(){
      document.getElementsByClassName('navigation')[0].classList.toggle("open");
    }
    .open{
      background-color: green;
      color: white;
    }
    Button
    
    

提交回复
热议问题