[javascript] childNode를 통해 루프

다음과 같이 childNodes를 반복하려고합니다.

var children = element.childNodes;
children.forEach(function(item){
    console.log(item);
});

그러나, 출력 Uncaught TypeError: undefined is not a function에 의한 forEach기능. 나는 또한 children대신 사용하려고 childNodes하지만 아무것도 변경되지 않았습니다.

무슨 일인지 아는 사람 있나요?



답변

변수 childrenNodeList인스턴스이고 NodeLists는 참이 아니므로 메서드를 Array상속하지 않습니다 forEach.

또한 일부 브라우저는 실제로 지원합니다. nodeList.forEach


ES5

slicefrom Array을 사용 NodeList하여을 적절한 Array.

var array = Array.prototype.slice.call(children);

단순히을 사용 하여 as 컨텍스트 call를 호출 forEach하고 전달할 수도 NodeList있습니다.

[].forEach.call(children, function(child) {});


ES6

당신이 사용할 수있는 from당신을 변환하는 방법을 NodeListArray.

var array = Array.from(children);

또는 다음 과 같이 스프레드 구문을... 사용할 수도 있습니다.

let array = [ ...children ];


사용할 수있는 해킹입니다 NodeList.prototype.forEach = Array.prototype.forEach그리고 당신은 사용할 수있는 forEach모든으로 NodeList그들에게 때마다 변환 할 필요없이.

NodeList.prototype.forEach = Array.prototype.forEach
var children = element.childNodes;
children.forEach(function(item){
    console.log(item);
});

좋은 설명과이를 수행하는 다른 방법은 NodeLists, Arrays, NodeLists 변환 및 DOM 이해에 대한 포괄적 인 내용을 참조하십시오 .


답변

나는 파티에 매우 늦었지만 이후 element.lastChild.nextSibling === null다음은 나에게 가장 간단한 옵션처럼 보입니다.

for(var child=element.firstChild; child!==null; child=child.nextSibling) {
    console.log(child);
}


답변

다음은 for-in루프를 사용 하여 수행하는 방법 입니다.

var children = element.childNodes;

for(child in children){
    console.log(children[child]);
}


답변

을 사용하여 다른 방법을 추가하는 것을 거부 할 수 없습니다 childElementCount. 주어진 부모에서 자식 요소 노드의 수를 반환하므로 반복 할 수 있습니다.

for(var i=0, len = parent.childElementCount ; i < len; ++i){
    ... do something with parent.children[i]
    }


답변

for루프로 시도하십시오 . forEach노드 모음이기 때문에 오류가 발생 nodelist합니다.

또는 노드 목록을 배열로 변환해야합니다.

function toArray(obj) {
  var array = [];
  for (var i = 0; i < obj.length; i++) {
    array[i] = obj[i];
  }
return array;
}

또는 이것을 사용할 수 있습니다

var array = Array.prototype.slice.call(obj);


답변

const results = Array.from(myNodeList.values()).map(parser_item);

NodeList는 Array가
아니지만 NodeList.values ​​()는 Array Iterator를 반환하므로 Array로 변환 할 수 있습니다.


답변

[역 순회]를 시도해보십시오.

var childs = document.getElementById('parent').childNodes;
var len = childs.length;
if(len --) do {
    console.log('node: ', childs[len]);
} while(len --);

OR [순회 순회]

var childs = document.getElementById('parent').childNodes;
var len = childs.length, i = -1;
if(++i < len) do {
    console.log('node: ', childs[i]);
} while(++i < len);