childNode를 통해 루프
다음과 같이 childNodes를 반복하려고합니다.
var children = element.childNodes;
children.forEach(function(item){
console.log(item);
});
그러나, 출력 Uncaught TypeError: undefined is not a function
에 의한 forEach
기능. 나는 또한 children
대신 사용하려고 노력 childNodes
하지만 아무것도 변경되지 않았습니다.
무슨 일인지 아는 사람 있나요?
변수 children
는 NodeList
인스턴스이고 NodeList
s는 참이 아니므로 메서드를 Array
상속하지 않습니다 forEach
.
또한 일부 브라우저는 실제로 지원합니다. nodeList.forEach
ES5
slice
from Array
을 사용 하여 를 NodeList
적절한 Array
.
var array = Array.prototype.slice.call(children);
단순히을 사용 하여 as 컨텍스트 call
를 호출 forEach
하고 전달할 수도 NodeList
있습니다.
[].forEach.call(children, function(child) {});
ES6
당신이 사용할 수있는 from
당신을 변환하는 방법을 NodeList
로 Array
.
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]);
}
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 [in order traversal]
var childs = document.getElementById('parent').childNodes;
var len = childs.length, i = -1;
if(++i < len) do {
console.log('node: ', childs[i]);
} while(++i < len);
Here is a functional ES6 way of iterating over a NodeList
. This method uses the Array
's forEach
like so:
Array.prototype.forEach.call(element.childNodes, f)
Where f
is the iterator function that receives a child nodes as it's first parameter and the index as the second.
If you need to iterate over NodeLists more than once you could create a small functional utility method out of this:
const forEach = f => x => Array.prototype.forEach.call(x, f);
// For example, to log all child nodes
forEach((item) => { console.log(item); })(element.childNodes)
// The functional forEach is handy as you can easily created curried functions
const logChildren = forEach((childNode) => { console.log(childNode); })
logChildren(elementA.childNodes)
logChildren(elementB.childNodes)
(You can do the same trick for map()
and other Array functions.)
If you do a lot of this sort of thing then it might be worth defining the function for yourself.
if (typeof NodeList.prototype.forEach == "undefined"){
NodeList.prototype.forEach = function (cb){
for (var i=0; i < this.length; i++) {
var node = this[i];
cb( node, i );
}
};
}
Couldn't resist to add another method, using childElementCount
. It returns the number of child element nodes from a given parent, so you can loop over it.
for(var i=0, len = parent.childElementCount ; i < len; ++i){
... do something with parent.children[i]
}
참고URL : https://stackoverflow.com/questions/24775725/loop-through-childnodes
'developer tip' 카테고리의 다른 글
급행 경로 매개 변수 조건 (0) | 2020.11.17 |
---|---|
섹션 헤더가 UITableView 일반 스타일에서 수행하는 것처럼 UICollectionView에서 Supplementary View를 플로팅하는 방법 (0) | 2020.11.17 |
jinja2 템플릿에서 jinja2 구문 이스케이프 (0) | 2020.11.17 |
Microsoft Edge가 일부 로컬 웹 사이트를 열지 만 다른 웹 사이트는 열지 않는 이유는 도메인 이름이 호스트 파일에서 127.0.0.1로 라우팅되는 이유 (0) | 2020.11.17 |
Angular 2에서 클릭 이벤트에 대한 함수 호출 (0) | 2020.11.17 |