Diego Oriani Diego Oriani - 2 months ago 9
HTML Question

How can I use arrays and JS to replace classes in a html element?

I am trying to make an interaction that replaces an element class with the next class in the array when the link is clicked. How can I do that?

Html

<a id="text" href="#">Change weights</a>
<h1>Hello world</h1>


Javascript

var weights = ["jHairline", "jThin", "jLight", "jRegular", "jMedium"];

document.getElementById('text').addEventListener('click', function(e) {
$("h1").each("weights");
e.preventDefault();
});


Thank you in advance.

Answer

You can something like

$(function() {
    var weights = ["jHairline", "jThin", "jLight", "jRegular", "jMedium"];
    //Variable to store the current class being pointed   
    var currentIndex = 0;

    //Bind click handler
    $('#text').on('click', function(e) {
        //Removes all classes and a
        $("h1").removeClass().addClass(weights[currentIndex]);

        //Reset to 0, if its last index
        if (currentIndex == weights.length)
            currentIndex = 0;
        else
            currentIndex++;

        e.preventDefault();
    });
});

DEMO