NodeList (จาก querySelectorAll, getElementsByClassName, ฯลฯ) เป็น array-like object ไม่ใช่ Array จริง — ไม่มี map, filter, reduce, forEach (ยกเว้น forEach ที่ NodeList มีอยู่แล้ว) ต้องแปลงเป็น Array ก่อนจึงจะใช้เมธอด Array ได้ครบ
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>NodeList to Array</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; margin: 5px;
}
</style>
</head>
<body>
<h1>แปลง NodeList เป็น Array ใน JavaScript</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">คลิกที่นี่</button>
<h3>กดปุ่มเพื่อเปลี่ยนสีทุก div ด้วย Array.from() + forEach</h3>
<script>
const sampEle = document.querySelectorAll(".sample");
const btnEle = document.querySelector(".Btn");
btnEle.addEventListener("click", () => {
// แปลง NodeList → Array
Array.from(sampEle).forEach(item => {
item.style.backgroundColor = "red";
});
});
</script>
</body>
</html>
ผลลัพธ์

เมื่อกดปุ่ม "คลิกที่นี่":

วิธีแปลง NodeList → Array
| วิธี | Syntax | รองรับ | หมายเหตุ |
|---|---|---|---|
| Array.from() | Array.from(nodeList) | ES2015+ | มาตรฐาน อ่านง่าย รองรับ Map function |
| Spread Operator | [...nodeList] | ES2015+ | สั้น กระชับ ใช้ได้กับ iterable ทุกชนิด |
| Slice | Array.prototype.slice.call(nodeList) | ES5+ | แบบเก่า ใช้ในโค้ดเก่า/IE |
| Array.apply | Array.apply(null, nodeList) | ES5+ | แบบเก่า |
| for...of | for (const el of nodeList) | ES2015+ | ไม่ต้องแปลง วนลูปได้เลย |
ตัวอย่างเพิ่มเติม
const nodes = document.querySelectorAll(".item");
// Array.from กับ map function (รวมแปลงค่าในขั้นเดียว)
const texts = Array.from(nodes, el => el.textContent.trim());
// Spread + filter/map
const visible = [...nodes].filter(el => el.offsetParent !== null);
const ids = [...nodes].map(el => el.id);
// for...of (ไม่ต้องแปลง)
for (const el of nodes) {
el.classList.add("active");
}
// NodeList.forEach (มีอยู่แล้ว ไม่ต้องแปลง)
nodes.forEach(el => el.style.color = "red");
HTMLCollection vs NodeList
getElementsByClassName,getElementsByTagName→ HTMLCollection (Live — อัปเดตอัตโนมัติเมื่อ DOM เปลี่ยน)querySelectorAll→ NodeList (Static — snapshot ตอน query)- ทั้งคู่แปลงเป็น Array ได้ด้วยวิธีเดียวกัน
⚠️ ข้อควรระวัง
- NodeList จาก
querySelectorAllเป็น Static — เปลี่ยน DOM แล้ว NodeList ไม่เปลี่ยน - HTMLCollection เป็น Live — ลบ element แล้ว length ลดลง, index เปลี่ยน → วนลูปลบต้องระวัง (วนย้อนกลับหรือใช้ while)
forEachของ NodeList ไม่รองรับbreak/continue— ใช้for...ofแทน