samedi 24 avril 2021

Why function 'runFunc("keyboard", "mouse")' change only three Classes

In this code, I made a function runFunc(previousClass, newClass) for changing class but only three classes changes by clicking a button. Why should we click button three times to change all the classes.

<div class="parent_class" id="parent">
    <div class="keyboard">1</div>
    <div class="keyboard">2</div>
    <div class="keyboard">3</div>
    <div class="keyboard">4</div>
    <div class="keyboard">5</div>
    <div class="keyboard">6</div>
</div>

<br><br>

<button onclick="runFunc('keyboard', 'mouse')">Change Class</button>

<script>

var a;

function runFunc(previousClass, newClass) {
var i;

var a1 = typeof previousClass;
var a2 = typeof newClass;

if (a1 === "string" && a2 === "string") {
    var a = document.getElementsByClassName(previousClass);
    console.log(a);

    for ( i = 0; i < a.length; i++ ) {
        a[i].className = newClass;
    }

    var b = document.getElementsByClassName(newClass);
    console.log(b);
    console.log("\n\n")
}
}

</script>
</body>



Aucun commentaire:

Enregistrer un commentaire