How to getElementByClass instead of GetElementById with JavaScript?

前端 未结 7 690
孤街浪徒
孤街浪徒 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';
         }
      }
    }
    
    0 讨论(0)
  • 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';
           }
         }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 09:42

    Append IDs at the class declaration

    .aclass, #hashone, #hashtwo{ ...codes... }
    document.getElementById( "hashone" ).style.visibility = "hidden";
    
    0 讨论(0)
  • 2020-11-22 09:49

    Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.

    Older Answer

    You'll want to check into jQuery, which will allow the following:

    $(".classname").hide(); // hides everything with class 'classname'
    

    Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(function(){
        $(".classname").hide();
      });
    </script>
    
    0 讨论(0)
  • 2020-11-22 09:54

    My solution:

    First create "<style>" tags with an ID.

    <style id="YourID">
        .YourClass {background-color:red}
    </style>
    

    Then, I create a function in JavaScript like this:

    document.getElementById('YourID').innerHTML = '.YourClass {background-color:blue}'
    

    Worked like a charm for me.

    0 讨论(0)
  • 2020-11-22 09:55
    document.getElementsByClassName('CLASSNAME')[0].style.display = 'none';
    

    Acyually by using getElementsByClassName, it returns an array of multiple classes. Because same class name could be used in more than one instance inside same HTML page. We use array element id to target the class we need, in my case, it's first instance of the given class name.So I've used [0]

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