1

I have a div which I want to toggle show on button click.

Here's the HTML structure :

<div>
<button onclick="toggle()"> Show </show>
<div id="toggle"> </div>
</div>

The script for this would be :

var div = document.getElementById("toggle");
if(div.style.display=="none" ||div.style.display == ""){
    div.style.display="block"   }
else{
    div.style.display="none";
    }

This works fine but what I I have multiple button-div combo ? Obviously I will have to use different id for each div but how will I get this id inside the function ? Or is there any other way ?

Also is this the right way to do it ? Using multiple id's for each div ? Is there any other way to implement such a system?

Aneesh
  • 1,703
  • 3
  • 24
  • 34

1 Answers1

1
function toggle(id) {
    var div = document.getElementById(id);
    if(div.style.display=="none" ||div.style.display == ""){
        div.style.display="block"   }
    else{
        div.style.display="none";
    }
}

And in your HTML

<div>
<button onclick="toggle('toggle')"> Show </show>
<div id="toggle"> </div>
</div>
user2520673
  • 118
  • 4
  • Ok this works. But is there any way to do this without using the id of the div ? Maybe change get the element after the button and modify it perhaps? I know its probably not there. – Aneesh Nov 07 '13 at 07:13
  • You can use `button + div` as css selector. This will select all divs that follow a button. See http://stackoverflow.com/questions/886863/best-way-to-find-dom-elements-with-css-selectors/4145389#4145389 – user2520673 Nov 07 '13 at 07:21