在 JavaScript 中通过 pure 在不同的 li 中添加类名?

javascriptweb developmentfront end technology

类是构建对象的模型。代码用于封装数据,以便对其进行处理。尽管 JS 类基于原型,但它们也具有一些 ES5 类所不具备的独特语法和语义。

让我们深入研究本文,以了解有关如何在 JavaScript 中通过 pure 在不同的 li 中添加类名的更多信息。要添加类,请使用 forEach() 和 classList.add()。

JavaScript 中的 forEach()

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

语法

以下是 forEach() 的语法

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

JavaScript 中的 classList.add()

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

语法

以下是 classList.add() 的语法

element.classList

为了更好地理解如何在 JavaScript 中通过 pure 在不同的 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 以不同的方式添加,该列表充当使用 Web 浏览器上的 classList.add() 方法添加的类。

示例

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

<!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 突出显示,当用户在网页上运行脚本时,事件被触发,CSS 充当类。

示例

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

<!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 应用的样式,因为事件使它们充当在网页列表中以不同方式添加的类。


相关文章