How to getElementByClass instead of GetElementById with JavaScript?

前端 未结 7 691
孤街浪徒
孤街浪徒 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

    The getElementsByClassName method is now natively supported by the most recent versions of Firefox, Safari, Chrome, IE and Opera, you could make a function to check if a native implementation is available, otherwise use the Dustin Diaz method:

    function getElementsByClassName(node,classname) {
      if (node.getElementsByClassName) { // use native implementation if available
        return node.getElementsByClassName(classname);
      } else {
        return (function getElementsByClass(searchClass,node) {
            if ( node == null )
              node = document;
            var classElements = [],
                els = node.getElementsByTagName("*"),
                elsLen = els.length,
                pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
    
            for (i = 0, j = 0; i < elsLen; i++) {
              if ( pattern.test(els[i].className) ) {
                  classElements[j] = els[i];
                  j++;
              }
            }
            return classElements;
        })(classname, node);
      }
    }
    

    Usage:

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

提交回复
热议问题