Toggle class to an element by click another element

前端 未结 5 2005
暗喜
暗喜 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:01

    You need to add event handlers. This can be done by simple setting the onClick property on the Element object:

    document.getElementById('button').onClick = function onClick() {
      document.getElementsByClassName('navigation')[0].className += 'open';
    };
    

    However, it's preferable that you use addEventListener so multiple event listeners can be added to the same element:

    document.getElementById('button').addEventListener('click', function onClick() {
      document.getElementsByClassName('navigation')[0].className += 'open';
    }, false);
    

    EDIT: It's also better to cache your element references in variables like so:

    var button = document.getElementById('button');
    var nav = document.getElementsByClassName('navigation')[0];
    
    button.addEventListener('click', function onClick() {
      nav.className += 'open';
    }, false);
    

    EDIT2: as in Zakaria's answer, you may want to use classList.add(x) instead of className += x. It's more in line with how jQuery's things work. However, be aware that classList is not supported in older versions of IE.

    EDIT3: Here's a final version using classList.toggle

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

    And here's a quick replacement for classList using className instead:

    function classList(elem) {
      var cl = {
        add: function (clas) { 
          elem.className += clas; 
        },
        remove: function (clas) { 
          elem.className = elem.className.replace(clas, ''); 
        },
        toggle: function (clas) {
          if (elem.className.indexOf(clas) > -1) {
            cl.remove(clas);
          } else {
            cl.add(clas);
          }
        }
      };
      return cl;
    }
    
    // usage
    classList(nav).add('open');
    classList(nav).toggle('open');
    
    0 讨论(0)
  • 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;
    }
    <a id="button">Button</a>
    
    <div class="navigation">
    Foo
    </div>

    0 讨论(0)
  • 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;
    }
    <a id="button">Button</a>
    
    <div class="navigation">Foo</div>
    <div class="navigation">Foo</div>
    <div class="navigation">Foo</div>

    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');
    });
    
    0 讨论(0)
  • 2021-01-16 10:16

    Try this:

    document.querySelector('div.navigation').classList.toggle('open');
    

    This will work if you only have one div element that has the class navigation. It would be better to give it an id, for example id=navigation

    0 讨论(0)
  • 2021-01-16 10:27

    You don't really need javascript. Checkboxes work great at storing on/off state. You just need to get a little crafty with the CSS to use it elsewhere. Here is an example:

    label.divcheck { color:blue; text-decoration:underline; }
    input.divcheck { display:none; }
    
    input.divcheck + div { display:none; }
    input.divcheck:checked + div { display:block;}
    <label class="divcheck" for="navigation">Button Nav</label>
    <label class="divcheck" for="other">Button Other</label>
    
    <input type="checkbox" class="divcheck" id="navigation"/>
    <div class="navigation">
    Foo
    </div>
    
    <input type="checkbox" class="divcheck" id="other"/>
    <div class="navigation">
    Other
    </div>

    0 讨论(0)
提交回复
热议问题