Easiest way to switch divs in html

Switch between Divs

In my project i had a container <div> where i wanted to display different content in this <div> according to some information dynamically. I tried several ways like changing the innerHTML by javascript or jQuery but it didn’t work, so my friend told me a nice trick that can helped me.

1- So, i had the container div as following


<div id="container">

</div>

2- add the sub divs to the container div with “display” values equal to “none”


<div id="container">

<div id="sub-container1" style="display:none">

</div>

<div id="sub-container2" style="display:none">

</div>

<div id="sub-container3" style="display:none">

</div>

</div>

3- with javascript when you want to show content of one div you run the following javascript


function myFunction () {
 $('#sub-container1').css("display","block");
 $('#sub-container2').css("display","none");
 $('#sub-container3').css("display","none");
 };

this will show the “sub-container1” div and hides the other sub-container if you’d like to show the second sub-container you make another function but set the display value of “sub-container2” to block and the others to none like this


function myFunction2 () {
 $('#sub-container1').css("display","none");
 $('#sub-container2').css("display","block");
 $('#sub-container3').css("display","none");
 };

and so on,

 

UPDATE

another and cleaner way as suggested by Sakr can be found here. many Thanks to him 🙂

Hope it helped 🙂