0

Im working with this part of code:

<div class="tabs-buttons-container">
            <button class="tabs-button" onclick="openTabs(event, 'test11', 'red')">Tab 1</button>
            <button class="tabs-button" onclick="openTabs(event, 'test12')">Tab 2</button>
            <button class="tabs-button" onclick="openTabs(event, 'test13')">Tab 3</button>
            <span class="test"></span>
            <span class="red"></span>
            <span class="white"></span>
        </div>
const openTabs = (event, tab, test) => {
    let i, tabContent, tabButton;

    tabContent = document.getElementsByClassName("tabs-content")

    for (i = 0; i < tabContent.length; i++) {
        tabContent[i].style.display = "none";
    }

    document.getElementById(tab).style.display = "block";
    document.getElementsByClassName(test).style.display = "block";
}

My current goal is to pass class "red" into function and change the display of span element. When im using ID it works fine but when i want to pass class the result is null. Is this possible to dynamically pass class name inside JS function?

2 Answers 2

1

getElementsByClassName return a collection, so you need to go through each element to assign the style. You can also use querySelector("." + className) which return only the first matched element.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh i've totaly forgot about that. Thank you!
0
var red = document.getElementByClassName('red')[0];

2 Comments

Code only answers can almost always be improved by the addition of some explanation of how and why they work?
Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. From Review

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.