使用纯JavaScript在不同的li元素中添加类名?


类作为构建对象的模型。代码用于封装数据,以便对其进行处理。虽然JS类基于原型,但它们也有一些ES5类不共享的独特的语法和语义。

让我们深入了解这篇文章,学习如何在纯JavaScript中为不同的li添加类名。要添加类,请使用forEach()以及classList.add()。

JavaScript中的forEach()

对于数组中的每个条目,forEach()方法都会调用不同的函数。处理空元素时,不使用此方法。给定函数可以对给定数组的元素执行任何操作。

语法

以下是forEach()的语法

array.forEach(function(currentValue, index, arr), thisValue)

JavaScript中的classList.add()

classList属性表示充当类元素值的DOMTokenList对象。虽然它是一个只读属性,但我们可以通过修改程序的类来更改其值。可以使用classList.add()方法向元素添加一个或多个类。

语法

以下是classList.add()的语法

element.classList

为了更好地理解如何在纯JavaScript中为不同的li添加类名。

示例

在下面的示例中,我们正在运行脚本以在不同的li中添加类名。

<!DOCTYPE html>
<html>
   <style>
      .color1 {
         color: #85C1E9 ;
      }
      .color2 {
         color: #F1C40F ;
      }
   </style>
<body>
   <ul>
      <li>MSD</li>
      <li>SKY</li>
      <li>ABD</li>
   </ul>
   <script>
      addClass();
      function addClass() {
         const list = document.querySelectorAll('li');
         list.forEach(function(task, index) {
            if (index === 0) {
               task.classList.add('color1');
            } else if (index === 2) {
               task.classList.add('color2');
            }
         });
      }
   </script>
</body>
</html>

当脚本执行时,它将生成一个输出,其中包含一个列表,其中项目使用带样式的CSS不同地添加,该CSS充当通过在web浏览器上使用classList.add()方法添加的类。

示例

在下面的示例中,我们使用document.querySelector('li:nth-of-type()')来更新单个元素的类。

<!DOCTYPE html>
<html>
   <style>
      .color1 {
         color: #BB8FCE ;
      }
      .color2 {
         color: #EC7063 ;
      }
   </style>
<body>
   <ul>
      <li>SUPERMAN</li>
      <li>SPIDERMAN</li>
      <li>BATMAN</li>
   </ul>
   <script>
      addClass();
      function addClass() {
         const firstLi = document.querySelector('li:nth-of-type(1)');
         firstLi.classList.add('color1');
         const secondLi = document.querySelector('li:nth-of-type(2)');
         secondLi.classList.add('color2');
      }
   </script>
</body>
</html>

运行上述脚本后,输出窗口将弹出,显示列表,其中一些用CSS突出显示,当用户在网页上运行脚本时,事件会触发,使其充当类。

示例

让我们考虑另一个可以使用firstElementChild和nextElementSibling的示例。

<!DOCTYPE html>
<html>
   <style>
      .color1 {
         color: #DFFF00 ;
      }
      .color2 {
         color: #CCCCFF ;
      }
   </style>
<body>
   <ul id="list">
      <li>JACK</li>
      <li>ROSE</li>
      <li>SPARROW</li>
   </ul>
   <script>
      function addClass()
      {
         const list = document.getElementById("list");
         list.firstElementChild.classList.add("color1");
         list.firstElementChild.nextElementSibling.classList.add("color2");
      }
      addClass();
   </script>
</body>
</html>

当脚本执行时,事件被触发并显示一个列表以及一些使用CSS应用的样式,因为事件使它们充当在网页上的列表中不同添加的类。

更新于:2023年1月18日

2K+ 次查看

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.