Show/hide 'div' using JavaScript

manipulate the elements by toggling between styling rather than changing the elements based on the innerHTML http://stackoverflow.com/questions/21070101/show-hide-div-using-javascript

by Damith Nuwan Sampath

HTML

<ul class="menu">
    <li class="toggle1">One</li>
    <li class="toggle2">Two</li>
    <li class="toggle3">Three</li>
    <li class="toggle4">Four</li>
    <li class="toggle5">Five</li>
</ul>
<div class="container">
    <div class="toggle1">Here are the contents of 1.</div>
    <div class="toggle2">Here are the contents of 2..</div>
    <div class="toggle3">Here are the contents of 3...</div>
    <div class="toggle4">Here are the contents of 4....</div>
    <div class="toggle5">Here are the contents of 5.....</div>
</div>

CSS

.menu > li {
    display:inline-block;
    font-weight:bold;
    padding:6px 10px;
    cursor:pointer;
    border:2px solid tomato;
    margin:5px;
}
.container {
    border:2px solid black;
    margin:5px;
}
.container > div {
    display:none;
}
.container > div:first-child {
    display:block;
}

JavaScript

var menu_elements = document.querySelectorAll('.menu>li'),
    menu_length = menu_elements.length;
for (var i = 0; i < menu_length; i++) {
    menu_elements[i].addEventListener('click', function (e) {
        var target = document.querySelector('.container>.' + e.target.classList[0]); // clicked element
        Array.prototype.filter.call(target.parentNode.children, function (siblings) {
            siblings.style.display = 'none'; // hide sibling elements
        });
        target.style.display = 'block'; // show clicked element
    });
}