How to getElementByClass instead of GetElementById with JavaScript?
Asked Answered
A

8

104

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 problem is that the script only uses getElementById, as getElementByClass is not supported in JavaScript. And unfortunately I do have to use class and not id to name the DIVs because the DIV names are dynamically generated by my XSLT stylesheet using certain category names.

I know that certain browsers now support getElementByClass, but since Internet Explorer doesn't I don't want to go that route.

I've found scripts using functions to get elements by class (such as #8 on this page: http://www.dustindiaz.com/top-ten-javascript/), but I can't figure out how to integrate them with with my toggle script.

Here's the HTML code. The DIVs themselves are missing since they are generated on page load with XML/XSLT.

Main Question: How do I get the below Toggle script to get Element by Class instead of get Element by ID?

<html>

<head>

<!--This is the TOGGLE script-->
<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>

</head>

<!--the XML/XSLT page contents will be loaded here, with DIVs named by Class separating dozens of li's-->

<a href="#" onclick="toggle_visibility('class1');">Click here to toggle visibility of class 1 objects</a>

<a href="#" onclick="toggle_visibility('class2');">Click here to toggle visibility of class 2 objects</a>

</body>
</html>
Afteryears answered 19/12, 2009 at 17:38 Comment(1)
Why haven't I been using jQuery all along?I took @Jonathan Sampson's suggestion of using jQuery, and it works! (CMS's answer was the one I thought I was looking for, but couldn't get it to work) I've given each link an id, and with jQuery I can define which classes show and which classes are hidden when you click on a particular link. GREAT! This solution seems too good to be true. jQuery seems too good to be true. What are the drawbacks of using jQuery? As a novice, why would I use Javascript instead of jQuery?Afteryears
C
82

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>
Cynicism answered 19/12, 2009 at 17:40 Comment(5)
Although good, the Google hosted jQuery is useful only for the most simple things, because of the cross-site scripting security implemented by most modern browsers.Swimmingly
You may also download the source file from jQuery.com and reference it locally.Cynicism
@Paulo: Cross-site scripting is not applicable for <script> tags. Google hosted jQuery is designed specifically for production websites (as a CDN). If your site is https, just make sure you use the https version to avoid mixed content warning.Cockrell
In fact, <script> tag injection is the basis of cross-site JSONP requests.Cockrell
Paulo, you do realize that once you include jQuery with the <script> tag, there are no cross-site restrictions at all?Emmott
S
89

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';
     }
  }
}
Shunt answered 19/12, 2009 at 17:45 Comment(2)
Why do you use that inner function instead of just plain code?Nam
-1 for example usage assuming that all elements on the screen have block display. In toggle_visibility, if e is a <span> then it should be 'inline' not 'block'. A much more robust solution is to define a CSS class: .invisible { display: none !important } and use JavaScript (or jQuery) to assign and unassign that class from elementsCutshall
C
82

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>
Cynicism answered 19/12, 2009 at 17:40 Comment(5)
Although good, the Google hosted jQuery is useful only for the most simple things, because of the cross-site scripting security implemented by most modern browsers.Swimmingly
You may also download the source file from jQuery.com and reference it locally.Cynicism
@Paulo: Cross-site scripting is not applicable for <script> tags. Google hosted jQuery is designed specifically for production websites (as a CDN). If your site is https, just make sure you use the https version to avoid mixed content warning.Cockrell
In fact, <script> tag injection is the basis of cross-site JSONP requests.Cockrell
Paulo, you do realize that once you include jQuery with the <script> tag, there are no cross-site restrictions at all?Emmott
A
7
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]

Adiel answered 23/11, 2017 at 8:33 Comment(0)
I
4

Use it to access class in Javascript.

<script type="text/javascript">
var var_name = document.getElementsByClassName("class_name")[0];
</script>
Ibadan answered 28/6, 2016 at 10:4 Comment(0)
P
2

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';
       }
     }
  }
}
Prater answered 16/9, 2010 at 17:28 Comment(0)
T
1

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.

Tegan answered 17/4, 2013 at 18:46 Comment(1)
Line breaks (<br>) are useless/invalid within a style tagDeckard
S
1

You can get the same result using document.querySelectorAll('.klass') as document.getElementsByClassName(klass).

It might not seem like much but querySelectorAll allows queries on any CSS selector which makes it much more flexible, in case "get all elements by class name" is just a step in what you are really trying to do. It is vanilla JS answer to jQuery's $('.class').

Source:

https://mcmap.net/q/211632/-how-to-get-all-elements-by-class-name-duplicate

Sidran answered 11/11, 2022 at 15:43 Comment(0)
F
0

For quick view in console, in below code viewing all elements text

for (let element of document.getElementsByClassName('classname')) {
    console.log(element.text);
}
Fighterbomber answered 17/1, 2023 at 11:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.