Skip to content
Advertisement

How to select all elements with a class in JS

I’d like to modify all classes with JS. Is there way to select them without manually setting the array index (for example [0] or [1] or [184])?

Example code:

<div class='message'>something:</div>
<div class='message'>something</div>
const element = document.querySelectorAll(".message");
element.classList.add("color");

It works only when I add [0] and only for the first element that has the class. But I’d like to modify all the elements with the class.

Advertisement

Answer

It’s important to learn what basic language syntax does first. The [0] is selecting the 0 index of an array (or array-like object). So to operate on them all, you can use a loop with a variable that is incremented starting at 0 and continuing until it goes out of bounds of the array.

function replaceEmotes() {
    var messages = document.querySelectorAll(".message");
    for (var i = 0; i < messages.length; i++) {
        var str = messages[i].innerHTML.replace(":smile:", "<i class='em em-smile'></i>");
        messages[i].innerHTML = str;
    }
}

There are other ways too, but this is a fundamental syntax that should probably be learned first.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement