javascript - 根据javascript中数组中的索引将css类添加到子元素

标签 javascript css arrays html

我有一个 Javascript 索引数组,例如 [0, 2]

还有一堆这样的段落元素

<div>
  <p>some text</p>
  <p>some more text</p>
  <p>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

将 css 类添加到索引出现在数组中的段落的简洁方法是什么?在这种情况下,我希望在第一段和第三段中添加一个类。

预期输出:

<div>
  <p class=“red”>some text</p>
  <p>some more text</p>
  <p class=“red”>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

最佳答案

使用querySelectorAll 并检查索引:

const arr = [0, 2];
const parent = document.getElementById("parent");
parent.querySelectorAll("p").forEach((elem, idx) => arr.includes(idx) ? elem.classList.add("red") : elem);
.red {
  color: red;
}
<div id="parent">
  <p>some text</p>
  <p>some more text</p>
  <p>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

旧版浏览器:

var arr = [0, 2];
var parent = document.getElementById("parent");
parent.querySelectorAll("p").forEach(function(elem, idx) {
  if (arr.indexOf(idx) > -1) {
    elem.classList.add("red");
  }
});
.red {
  color: red;
}
<div id="parent">
  <p>some text</p>
  <p>some more text</p>
  <p>some sample text</p>
  <p>some text here</p>
  <p>some great text</p>
</div>

关于javascript - 根据javascript中数组中的索引将css类添加到子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55843002/

相关文章:

javascript - 如何在响应式中更改 div 位置

html - Flex 切断子项

php - 我应该使用数组还是对象

javascript - NodeJS 包依赖

Javascript 正则表达式从句子中检索变量

javascript - 如何从 ASP.NET 委托(delegate)执行 Response.Redirect

iphone - 具有宽 iframe 的网页在具有视口(viewport)的 iPhone 上不可滚动

c - C程序在执行函数时崩溃

创建指针数组

javascript - CSS 变量和转换