The Simpliest Way to Create Pure JavaScript Tabs on your Website
I saw a lot of decisions all over the web. And all of them was not simple enough. Then I had an idea to create a very simple function which allows to create and switch the tabs on your website.
First of all lets look at tabs html:
<ul>
<li><a href="javascript:rudrSwitchTab('tb_1', 'content_1');" id="tb_1" class="tabmenu active">Tab 1</a></li>
<li><a href="javascript:rudrSwitchTab('tb_2', 'content_2');" id="tb_2" class="tabmenu">Tab 2</a></li>
</ul>
<div id="content_1" class="tabcontent">
Content of the first tab.
</div>
<div id="content_2" class="tabcontent" style="display:none;">
Content of the second tab.
</div>
The next step is a JavaScript function, you can insert it anywhere on the page (do not forget about <script>
tags) or to another js file.
function rudrSwitchTab(rudr_tab_id, rudr_tab_content) {
// first of all we get all tab content blocks (I think the best way to get them by class names)
var x = document.getElementsByClassName("tabcontent");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.display = 'none'; // hide all tab content
}
document.getElementById(rudr_tab_content).style.display = 'block'; // display the content of the tab we need
// now we get all tab menu items by class names (use the next code only if you need to highlight current tab)
var x = document.getElementsByClassName("tabmenu");
var i;
for (i = 0; i < x.length; i++) {
x[i].className = 'tabmenu';
}
document.getElementById(rudr_tab_id).className = 'tabmenu active';
}
That’s it. You can now add a bit of CSS rules and then your tabs will be ready.

Misha Rudrastyh
Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me
Thanks a lot !
“And all of them was not simple enough.” i agree 100%! this was perfect for my needs, it took 2 seconds to set up & 2 more to style. thanks a lot!!! :))
Great job! thanks a lot.
Great post, thanks for sharing this Misha.
Thanks for this,
just a question: is there a way to “scroll to content” on click?, I’m using this with images for tabs, and sometimes the tabs section gets too big on mobile, hiding the content.
Thanks again.
Hey,
Try this:
Dude!!! This helped a ton. Thanks for doing this quick write up.
Thanks. Helped a lot. Easy setup.
Wow, thanks so much. You helped me big time!
Braide, from Nigeria