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

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

Follow me on Twitter