Show one or more items and their contents that were hidden

I'm stuck and not sure how to move on. I want to be able to click a tab to open its contents. With the code that I have, when I click on one tab, it shows contents for all tabs. But I just want the click to show the content associated with this single tab. I am looking for a solution for vanilla javascript.

Here's the code: http://codepen.io/anon/pen/KCJAc (in the line below)

CSS

.tab-content {
    display: block;
    height: 0;
    opacity: 0;
    overflow: hidden;
    transition: all 1s ease-out;
}

.tab-active {
    height: auto;
    opacity: 1;
}

JavaScript:

var tabHeaders = document.getElementsByClassName('tab-header');
for (var i = 0; i < tabHeaders.length; i++) {
    tabHeaders[i].addEventListener('click', activateTab);
}

function activateTab() {
    var tabContents = document.getElementsByClassName('tab-content');
    for (var i = 0; i < tabContents.length; i++) {
        tabContents[i].classList.add('tab-active');
    }
}

HTML:

<div>
  <h3 class="tab-header">Tab1</h3>
  <p class="tab-content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium odio iste aliquam molestias corporis blanditiis nihil soluta sint illum quibusdam reprehenderit sed quaerat iusto maiores error iure ducimus dicta ipsum.</p>
</div>

<div>
  <h3 class="tab-header">Tab2</h3>
  <p class="tab-content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium odio iste aliquam molestias corporis blanditiis nihil soluta sint illum quibusdam reprehenderit sed quaerat iusto maiores error iure ducimus dicta ipsum.</p>
</div>
+3
source share
2 answers

You add tab-activeto all of the elements tab-content. You just want to add it to the next heading that you clicked: Updated pen

var tabHeaders = document.getElementsByClassName('tab-header');
for (var i = 0; i < tabHeaders.length; i++) {
    tabHeaders[i].addEventListener('click', activateTab);
}

function activateTab() {
    var tabContents = this.nextElementSibling;
    while (tabContents && (!tabContents.classList || !tabContents.classList.contains("tab-content"))) {
        tabContents = tabContents.nextElementSibling;
    }
    if (tabContents) {
        tabContents.classList.toggle("tab-active");
    }
}

:

  • nextElementSibling, , , classList , , . , nextSibling ( className, classList).
+2

, document.getElementsByClassName tab-content , DOM tab-header. nextSibling tab-header, DOM node tab-header:

function activateTab() {
    this.nextSibling.classList.add("tab-active");
}

, , tab-content tab-header, parentNode querySelector:

function activateTab() {
    this.parentNode.querySelector(".tab-content").classList.add("tab-active");
}

, IE8, classList .

+1

All Articles