How to getElementByClass instead of GetElementById with JavaScript?

前端 未结 7 703
孤街浪徒
孤街浪徒 2020-11-22 09:33

I\'m trying to toggle the visibility of certain DIV elements on a website depending on the class of each DIV. I\'m using a basic JavaScript snippet to toggle them. The probl

7条回答
  •  逝去的感伤
    2020-11-22 09:41

    adding to CMS's answer, this is a more generic approach of toggle_visibility I've just used myself:

    function toggle_visibility(className,display) {
       var elements = getElementsByClassName(document, className),
           n = elements.length;
       for (var i = 0; i < n; i++) {
         var e = elements[i];
    
         if(display.length > 0) {
           e.style.display = display;
         } else {
           if(e.style.display == 'block') {
             e.style.display = 'none';
           } else {
             e.style.display = 'block';
           }
         }
      }
    }
    

提交回复
热议问题