Jump to content

toggle multiple divs same id


Recommended Posts

hello, who can help and me.

how can I make a button, to show and hide one div with same id.

i use this.

<script language="javascript"> 
function toggle() {
	var ele = document.getElementById("main");
	var text = document.getElementById("displayText");
	if(ele.style.display == "block") {
    		ele.style.display = "none";
		text.innerHTML = "Show";
  	}
	else {
		ele.style.display = "block";
		text.innerHTML = "Hide";
	}
} 
</script>

but have one problme,show only the first div.

 

<div id="baraName">
<b>Test</b>          
<div id="texbutton">
<a id="displayText" ; href="javascript:toggle();">show</a> 
</div>
</div>
<div id="main" hidden>
blablabla</div>



<div id="baraName">
<b>Test22</b>          
<div id="texbutton">
<a id="displayText" ; href="javascript:toggle();">show</a> 
</div>
</div>
<div id="main" hidden>
asaaxaxazaxacacaca</div>

 

Link to comment
Share on other sites

First of all: This can't work because ids can only exist once! If you want to do such things you have to give the divs classes!

So, I would do that with jQuery. It is just a lot easier for beginner than native JavaScript like you did.

If you want to show/hide divs with its own toggle button (dynamically) you can do it like i did here:

I used "data" Attribute for trigger the related div. The coole thing is, that you can place your div wherever you want and it works on several divs if you want. Just use the class which is used in the data Attribute for one or more divs.

Shoud be easy to understand:

<button class="toggleButton" data-toggle="div1">Show</button>
<div class="toggleDiv div1">First Container</div>

 

  • Love 1
Link to comment
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now

Announcements



×
×
  • Create New...

Important Information

Terms of Use / Privacy Policy / Guidelines / We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.