13

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.

Oliver
  • 341
  • 2
  • 4
  • 21
  • 1
    Instead of using [0] you need to loop all the elements and use [0] to change the inner html of each element – mylee Mar 23 '19 at 15:28
  • see this article: https://stackoverflow.com/questions/15843581/how-to-correctly-iterate-through-getelementsbyclassname – Benjamin Mar 23 '19 at 15:29

4 Answers4

16

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.

ziggy wiggy
  • 1,039
  • 6
  • 6
6

Use forEach to iterate over all message nodes and replace emotes. Also note that I'm using a global regexp to replace all :smile: strings within a message, not just the first one.

function replaceEmotes() {
    var messages = document.querySelectorAll(".message");

    messages.forEach(message => {
       message.innerHTML = message.innerHTML.replace(/:smile:/g, "<i class='em em-smile'></i>");
    });
}
abadalyan
  • 1,205
  • 8
  • 13
4

document.querySelectorAll() selects all elements of given class name and store them in an array-like object. It is possible to loop through the objects instead of accessing them manually.

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

You can also do the same thing using document.getElementsByClassName()

var elements = document.getElementsByClassName('className');
for(var i = 0; i < elements.length; i++){
    // Same like above...
}
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
Adnan Toky
  • 1,756
  • 2
  • 11
  • 19
2

you can use document.getElementsByClassName("message") and loop through all the elements in the NodeList

jenil christo
  • 666
  • 8
  • 16