如何使用JS中的类选择所有元素 [英] How to select all elements with a class in JS

查看:51
本文介绍了如何使用JS中的类选择所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用JS修改所有类.是否可以不用手动设置数组索引(例如[0]或[1]或[184])来选择它们?

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])?

示例代码:

<div class='message'>something:</div>
<div class='message'>something</div>

const element = document.querySelectorAll(".message");
element.classList.add("color");

它仅在我添加 [0] 时有效,并且仅适用于具有该类的第一个元素.但是我想用该类修改所有元素.

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.

推荐答案

重要的是要先学习基本语言语法. [0] 选择数组(或类似数组的对象)的 0 索引.因此,要对它们全部进行操作,可以使用带有变量的循环,该变量从 0 开始递增,一直持续到超出数组范围为止.

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.

这篇关于如何使用JS中的类选择所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆