如何將節點列表轉換為 JavaScript 中的陣列?


以下是在 JavaScript 中將節點列表轉換為陣列的程式碼 −

示例

 動態演示

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      display: inline-block;
      font-size: 20px;
      font-weight: 500;
      color: white;
      background-color: blue;
      padding:10px;
      width: 100px;
      height: 100px;
   }
</style>
</head>
<body>
<h1>Convert a node list to an array</h1>
<div class="sample">1</div>
<div class="sample">2</div>
<div class="sample">3</div>
<div class="sample">4</div>
<br>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to change colors of all the above div </h3>
<script>
   let sampEle = document.querySelectorAll('.sample');
   let BtnEle = document.querySelector('.Btn');
   BtnEle.addEventListener('click',()=>{
      Array.from(sampEle).forEach(item=>{
         item.style.backgroundColor = 'red';
      })
   })
</script>
</body>
</html>

輸出

點選“點選此處”按鈕 −

更新於:17-7-2020

302 次瀏覽

開啟您的 職業生涯

完成課程以獲得認證

立即開始
廣告