Get Element By Classname Script Not Working

I wrestled a bear once. picture I wrestled a bear once. · Nov 6, 2012 · Viewed 23.6k times · Source

I know, it's not supported by IE, but I found a cool script online that someone was generous enough to provide for free, but I can't figure out why it's not working. I've been staring at this for hours, please point me in the right direction!

My code:

<script language="javascript" type="text/javascript" src="getbyclass.js"></script>
<script type="text/javascript" language="javascript">
function editToggle(toggle){
    if (toggle == "off"){
    getElementsByClassName("editp").style.display ="none";
    document.getElementById('editToggle').innerHTML="<a href=\"#\" onclick=\"editToggle(\"off\"); return false;\">>Edit Mode: <span style=\"color:red;\">OFF</span></a>";
    toggle="on";
    }else{
    getElementsByClassName("editp").style.display ="inline";
    document.getElementById('editToggle').innerHTML="<a href=\"#\" onclick=\"editToggle(\"on\"); return false;\">>Edit Mode: <span style=\"color:green;\">on</span></a>";
    toggle="off";
    }
}

also:

echo "<span id=\"editToggle\"><a href=\"#\" onclick=\"editToggle(); return false;\">Edit Mode: <span style=\"color:red;\">OFF</span></a></span>";

The code from getbyclass.js can be seen here.


In response to the answers below, I've tried this:

function editToggle(toggle){
    var list = getElementsByClassName("editp");
    if (toggle == "off"){
    //getElementsByClassName("editp").style.display ="none";
        for (index = 0; index < list.length; ++index) {
            list[index].style.display ="none";
        }
    document.getElementById('editToggle').innerHTML="<a href=\"#\" onclick=\"editToggle(\"off\"); return false;\">>Editfalse;\">Edit Mode: <span style=\"color:red;\">OFF</span></a>";
    toggle="on";
    }else{
    //getElementsByClassName("editp").style.display ="inline";
        for (index = 0; index < list.length; ++index) {
            list[index].style.display ="inline";
        }
    document.getElementById('editToggle').innerHTML="<a href=\"#\" onclick=\"editToggle(\"on\"); return false;\">>Editfalse;\">Edit Mode: <span style=\"color:green;\">on</span></a>";
    toggle="off";
    }
}

But it's still not working.

Answer

Talha picture Talha · Nov 6, 2012

getElementsByClassName returns a collection. You might need to loop through the results, like this:

var elements = document.getElementsByClassName('editp');
for(var i=0; i<elements.length; i++) { 
  elements[i].style.display='none';
}
  • elements is a live NodeList of found elements in the order they appear in the tree.
  • names is a string representing the list of class names to match; class names are separated by whitespace
  • getElementsByClassName can be called on any element, not only on the document. The element on which it is called will be used as the root of the search.

Should go through this.