How to create tabs in HTML using jQuery

jQuery is a versatile javascript library that is used to do a lot of things. However, its main purpose is to make DOM manipulation easier.

In this answer, jQuery is used to create tabs in HTML with its simple and understandable syntax.

Now let’s get to it!

Suppose we have a tab in HTML as below:

Tabs using HTML

Upon running the code above, the tabs and all their contents will be displayed at the same time on the screen. This display is not the best practice as the user will be confused as to which of the tabs’ content to check first.

How can a developer solve this issue?

A good solution would display the first tab’s content on loading, and the other tabs’ content should be displayed only when clicked.

Now, let’s do this with jQuery.

Example

Tabs using HTML and jQuery

Explanation

  • Line 3: This line hides all the elements with the class tabContent except for the first element. The code will search for all the elements with the specified class and hide all of them except the first element.

Note: The divs with the class tabContent hold the content of the tabs.

  • Line 7: Click event is attached to the link of all the elements with the .tabs class such that when you click on the link, the included callback function will be called.

  • Line 10: Hides all the elements with the class tabContent. This line marks the beginning of the callback function’s code block.

  • Line 13: This code line removes the active class from the tab’s link. The active class gives it a green color.

  • Line 16: This adds active class to the clicked link. this means clicked link.

  • Line 19: Here, jQuery gets the value of the data-tab attribute and assigns it to the variable tab.

Note: The .data() method is used to get the value of data-* attribute. Whatever * is passed into the .data() method to get its value.

  • Line 20: Concatenation between the # and the tab value equals the tab content’s ID. The show() method is attached to it to display the clicked link’s tab content.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved