English 中文(简体)
How to getElementByClass instead of GetElementById with JavaScript?
原标题:

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>
最佳回答

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>
问题回答

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 ;
     }
  }
}
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]

Use it to access class in Javascript.

<script type="text/javascript">
var var_name = document.getElementsByClassName("class_name")[0];
</script>

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 ;
       }
     }
  }
}

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.

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://stackoverflow.com/a/9427330/3850405

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

for (let element of document.getElementsByClassName( classname )) {
    console.log(element.text);
}




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签