set里面foreach的使用

55 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <p>第1个p</p>
    <p>第2个p</p>
    <p>第3个p</p>
    <p>第4个p</p>
    <p>第5个p</p>
  </body>
  <script>
    // 找到所有的p 相当于一个节点列表nodelist
    var pArr = document.querySelectorAll("p");
    // 把找到的类数组对象转成set
    const set = new Set(pArr);
    // 用forEach遍历set
    // forEach是set的一个方法,里面需要传入一个函数作为参数
    set.forEach(function (elements) {
      elements.style.color = "red";
      elements.style.backgroundColor = "red";
    });
  </script>
</html>