
NodeList는 원래 Array와 같은 구조를 가지는 컬렉션이 아닙니다. NodeList는 DOM 노드의 컬렉션을 나타내는 객체로, Array와 유사하지만 Array와는 다른 프로토タイプ 체인을 가지고 있습니다.
NodeList를 Array로 변환하여 사용할 수 있는 방법은 다음과 같습니다.
1. Array.from() 메서드를 사용할 수 있습니다.
#hostingforum.kr
javascript
const elements = Array.from(document.getElementsByClassName('btn'));
console.log(elements);
2. Array.prototype.slice() 메서드를 사용할 수 있습니다.
#hostingforum.kr
javascript
const elements = document.getElementsByClassName('btn');
console.log(elements.slice());
3. Array.prototype.concat() 메서드를 사용할 수 있습니다.
#hostingforum.kr
javascript
const elements = document.getElementsByClassName('btn');
console.log(Array.prototype.concat.apply([], elements));
4. Array.prototype.forEach() 메서드를 사용할 수 있습니다.
#hostingforum.kr
javascript
const elements = document.getElementsByClassName('btn');
elements.forEach(element => console.log(element));
5. Spread 연산자(...)를 사용할 수 있습니다.
#hostingforum.kr
javascript
const elements = document.getElementsByClassName('btn');
console.log([...elements]);
NodeList를 Array로 변환하여 사용할 수 있는 방법은 Array.from() 메서드를 사용하는 것이 가장 좋습니다. Array.from() 메서드는 NodeList를 Array로 변환하는 데 사용할 수 있는 가장 간단하고 효율적인 방법입니다.
2025-07-02 05:30