Function for Tooltip does not work when run a second time

1

I'm creating a schematic of tooltips, so when clicking on a certain span, this span shows a message

HTML

<div class="banner-tooltips" id="banner-tooltips">
    <span id="primeira-tooltip">1°</span>
    <span id="segunda-tooltip">2°</span>
    <span id="terceira-tooltip">3°</span>
    <span id="quarta-tooltip">4°</span>
</div>

JS

function tooltips(){
    var caixaTooltips=document.getElementById("banner-tooltips");
    var tooltips=caixaTooltips.querySelectorAll("span");
    for(var i=0;i<tooltips.length;i++){
        tooltips[i].addEventListener("click",function(){
            var anterior=document.getElementsByClassName("banner-tooltip-active");
            console.log(anterior);
            if(anterior.length!=0){
                console.log(anterior);
                anterior.classList.remove("banner-tooltip-active");
            }
            console.log(anterior);
            this.classList.add("banner-tooltip-active");
        });
    }
}
tooltips();

When you click on the first tooltip, it opens a good one, however, when you click it a second time, it says that you can not remove the undefined class. Why does this occur, and how can I resolve the problem?

    
asked by anonymous 22.03.2017 / 13:00

1 answer

2

Probably in the first click does not have any element with class banner-tooltip-active , but in the second yes, and this error is generated because document.getElementsByClassName("banner-tooltip-active"); will return an array , then anterior.classList it will not work. I suggest changing this section:

if(anterior.length){
    for (let i = 0 ; i < anterior.length ; i++){
        anterior[i].classList.remove("banner-tooltip-active");
    }
}

In this way it will iterate all other span by removing the active style, and finally enable only what was clicked.

    
22.03.2017 / 13:07