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">


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 id="sub-container2" style="display:none">


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



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

function myFunction () {

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 () {

and so on,



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

Hope it helped 🙂


9 responses to “Easiest way to switch divs in html

  1. I found something similar elsewhere and really found it helpful. Some more of this please! Thanks very much

  2. This was cool, thanks!

    I think you should consider using code highlighting when posting code samples like this one, Google syntax highlighting in WordPress, there’s an article about it in the Codex.

  3. A cleaner way would be to have the following DOM

    .subcontainer {
    display: none;

    And the following JS

    show_subcontainer = function(number) {
    $('#subcontainer-' + number).show()

    And to show whichever subcontainer you’d simply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: