0

I need to get more than one element to toggle open and closed. Right now the function is just selecting the ID, but I'd like to know how to get it to select a class. I thought I could change the document.getElementById to document.getElementByClass but that didn't work.

I picked this bit of code during my search:

#ToggleTarget {display:hidden;}

<script type="text/javascript">
function Toggle() {
    var el = document.getElementById("ToggleTarget");
    if (el.style.display == "block") {
        el.style.display = "none";
    }
    else {
        el.style.display = "block";
    }
}
</script>
Gijs
  • 5,201
  • 1
  • 27
  • 42

1 Answers1

1
var getElementsByClassName = function(node, classname) {
    if (document.getElementsByClassName) { 
        return document.getElementsByClassName(classname);
    }
    var a = [];
    var re = new RegExp('(^| )'+classname+'( |$)');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

var Toggle = function(){
    var tp = getElementsByClassName(document.documentElement,'toggle');
        for(var i = 0; i < tp.length; i++){
            if(tp[i].style.display=='none')
                tp[i].style.display='block'
            else
                tp[i].style.display='none'
    }
}

Use getElementsByClassName and then loop through them.

EDIT

Just make sure they have the class toggle as used in my code above.

UPDATE

Added function for IE support (adopted from https://stackoverflow.com/a/7410966/600101).

Community
  • 1
  • 1
Henrik Ammer
  • 1,889
  • 13
  • 26
  • thanks henrik... the items i have expanding and collapsing are shut and won't open. is there a trigger to open the folders that i misplaced? – Ijan Hilaire Sep 12 '12 at 10:41
  • See this test, http://jsfiddle.net/v8AkV/2/. Do your items have `display:none` set in the CSS or in the `style` attribute of the tag? – Henrik Ammer Sep 12 '12 at 10:48
  • yeah, i had the code correct all along just typed it wrong here, unfortunately. when i apply this to my site the trigger basically refreshes the page. – Ijan Hilaire Sep 12 '12 at 10:58
  • But the jsfiddle I link to work even for you? Because if so, the answer is correct, then we need to check your implementation of it. – Henrik Ammer Sep 12 '12 at 11:01
  • right, the jsfiddle is what i want to do but, the problem is my code... would u like a link to see what kind of mess i made? – Ijan Hilaire Sep 12 '12 at 11:02
  • Add your code to http://jsfiddle.net and give me the link. Close/accept answer on this question since it has been answered and we are now moving on to something else (which is code debugging :). – Henrik Ammer Sep 12 '12 at 11:24
  • Then go to http://webchat.quakenet.org/, set your nick and set channel to #stackoverflow so we can discuss it more easier. – Henrik Ammer Sep 12 '12 at 11:30