How do I change multiple elements with same class name using Javascript?

后端 未结 6 991
无人共我
无人共我 2020-12-21 03:45

Follow up to my previous question - I want to use a button to show / hide multiple elements with the same class name using JS, yet it appears that I can only change the firs

6条回答
  •  -上瘾入骨i
    2020-12-21 04:40

    getElementsByClassName return an array of elements. You have to iterate them and update their style one by one

    var elements = {
      design: document.getElementsByClassName("design"),
      it: document.getElementsByClassName("it"),
      other: document.getElementsByClassName("other")
    };
    
    function toggle(type) {
      Object.keys(elements).forEach(function(key) {
        var els = elements[key];
        var state = "none";
        if (key === type) state = "block";
        for (var i = 0; i < els.length; i++) {
          els[i].style.display = state;
        }
      });
    }
    .indent {
      margin: .5em 1em .5em 1em;
    }
    
    
    
    
    
    • boring IT stuff
    • cool design stuff
    • it stuff and things
    • design stuff
    • it stuff and more
    • more it stuff
    • it stuff

提交回复
热议问题