How to hide other tabs's content and display only the selected tab's content

54,227

Giving all the tab content elements a common CSS class makes selecting and styling them much easier, for example in this demo and code below.

CSS

.tabContent {
    display:none;
}

JavaScript

function showStuff(element)  {
    var tabContents = document.getElementsByClassName('tabContent');
    for (var i = 0; i < tabContents.length; i++) { 
        tabContents[i].style.display = 'none';
    }

    // change tabsX into tabs-X in order to find the correct tab content
    var tabContentIdToShow = element.id.replace(/(\d)/g, '-$1');
    document.getElementById(tabContentIdToShow).style.display = 'block';
}

HTML

<ul class="side bar tabs">
    <li id="tabs1" onclick="showStuff(this)">City</li>
    <li id="tabs2" onclick="showStuff(this)">Country</li>
    <li id="tabs3" onclick="showStuff(this)">Humanity</li>  
</ul>

<div id="tabs-1" class="tabContent">
    <p>Proin elit m</p>
</div>
<div id="tabs-2" class="tabContent">
    <p>M massa ut d</p>
</div>
<div id="tabs-3" class="tabContent">
    <p> sodales.</p>
</div>

I have also updated the showElement function to be more generic so that there is less code duplication when hiding and showing the correct tab content.

The only caveat is that getElementsByClassName() is not available in IE8 or below. Other (modern) browsers have this function but there are alternatives - see getElementsByClassName & IE8: Object doesn't support this property or method.

Share:
54,227
user1223844
Author by

user1223844

Updated on July 09, 2022

Comments

  • user1223844
    user1223844 almost 2 years

    When I click on a particular tab the other tabs's content should be hidden but it is not hiding. This is all the code I have.

    function showStuff(id) {
      if (document.getElementById(id).style.display === "block") {
        document.getElementById(id).style.display = "none";
      } else {
        document.getElementById(id).style.display = "block";
      }
    }
    <ul class="side bar tabs">
      <li id="tabs1" onclick="showStuff('tabs-1')">City</li>
      <li id="tabs2" onclick="showStuff('tabs-2')">Country</li>
      <li id="tabs3" onclick="showStuff('tabs-3')">Humanity</li>
    </ul>
    
    <div id="tabs-1" style="display : none">
      <p>Proin elit m</p>
    </div>
    <div id="tabs-2" style="display : none">
      <p>M massa ut d</p>
    </div>
    <div id="tabs-3" style="display : none">
      <p> sodales.</p>
    </div>