HTML Collection 요소의 루프용
모든 요소의 get id를 설정하려고 합니다.HTMLCollectionOf하다
var list = document.getElementsByClassName("events");
console.log(list[0].id);
for (key in list) {
console.log(key.id);
}
그러나 콘솔에 다음과 같은 출력이 있습니다.
event1
undefined
그건 내가 기대한게 아니야. 출력은 왜 " " " 입니다.undefined, 첫 은 " " " 입니다.event1
번째에는 '아예'를 사용하고 .for/in잘못되어 있습니다.의 코드, 신드,,,,,,, in in,key을 사용하다의사 배열에서 을 list[key] '아이디'를 하면 list[key].id이렇게 안 이렇게 하면 안 요.for/in★★★★★★★★★★★★★★★★★★.
개요 (2018년 12월 추가)
.for/innodeList 를 합니다.이를 회피하는 이유는 다음과 같습니다.
"Safari, Firefox, Chrome, Edge"를 지원합니다.for/of DOM 목록과 같은nodeList ★★★★★★★★★★★★★★★★★」HTMLCollection.
다음은 예를 제시하겠습니다.
var list = document.getElementsByClassName("events");
for (let item of list) {
console.log(item.id);
}
오래된 브라우저(IE 등)를 포함하려면 , 이것은 어디에서나 유효합니다.
var list = document.getElementsByClassName("events");
for (var i = 0; i < list.length; i++) {
console.log(list[i].id); //second console output
}
를 사용하지 for/in
for/in는 오브젝트의 속성을 반복하기 위한 것입니다.이는 객체의 모든 반복 가능한 속성을 반환한다는 것을 의미합니다.어레이(어레이 요소 또는 의사 배열 요소 반환)에 대해 작동하는 것처럼 보일 수 있지만 어레이와 유사한 요소에서 기대하는 것과 다른 개체의 속성을 반환할 수도 있습니다. and고거 and and?HTMLCollection ★★★★★★★★★★★★★★★★★」nodeList는 둘 다 수 .for/in★★★★ 이며, 하고 있는 리스트내의 (인덱스12 등)이 취득됩니다.★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★length ★★★★★★★★★★★★★★★★★」item★★★★★★for/inHTML Collection html html html html html 。
HTML 선택을 반복할 수 없는 이유에 대해서는, http://jsfiddle.net/jfriend00/FzZ2H/ 를 참조해 주세요.for/in.
「」의for/in반복은 다음 항목(개체의 반복 가능한 모든 속성)을 반환합니다.
0
1
2
item
namedItem
@@iterator
length
왜 쓰려고 수 거예요.for (var i = 0; i < list.length; i++) 그냥 '나'나 '나'가 나와요.0,1 ★★★★★★★★★★★★★★★★★」2를 참조해 주세요.
NodeList 및 HTMLCollection 반복에 대한 브라우저 지원의 진화
다음은 2015-2018년 동안 브라우저가 어떻게 진화했는지에 대한 진화를 통해 반복할 수 있는 추가적인 방법을 제시합니다.위에서 설명한 옵션을 사용할 수 있기 때문에 최신 브라우저에서는 이 중 어느 것도 필요하지 않습니다.
2015년 ES6 업데이트
에 추가되었습니다.Array.from()어레이와 같은 구조를 실제 어레이로 변환합니다.이를 통해 다음과 같이 직접 목록을 열거할 수 있습니다.
"use strict";
Array.from(document.getElementsByClassName("events")).forEach(function(item) {
console.log(item.id);
});
작업 데모(2016년 4월 현재 Firefox, Chrome 및 Edge) : https://jsfiddle.net/jfriend00/8ar4xn2s/
2016년 ES6 업데이트
를 ES6 할 수 .NodeList ★★★HTMLCollection코드에 추가하기만 하면 됩니다.
NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
다음 작업을 수행할 수 있습니다.
var list = document.getElementsByClassName("events");
for (var item of list) {
console.log(item.id);
}
이 기능은 현재 버전의 Chrome, Firefox 및 Edge에서 작동합니다.이는 어레이 리터레이터를 NodeList와 HTMLCollection 프로토타입에 모두 연결하여 반복할 때 어레이 리터레이터를 사용하여 반복하기 때문입니다.
작업 데모: http://jsfiddle.net/jfriend00/joy06u4e/
2016년 12월 ES6 2차 업데이트
12월 기준Symbol.iteratorChrome v54 및 Firefox v50에 대한 지원이 포함되어 있기 때문에 아래 코드는 자동으로 작동합니다.이치노
var list = document.getElementsByClassName("events");
for (let item of list) {
console.log(item.id);
}
작업 데모(Chrome 및 Firefox): http://jsfiddle.net/jfriend00/3ddpz8sp/
2017년 12월 ES6 3차 업데이트
2017년 12월 이 41 a 2017 12 월월월41.16299.15.0으로 .nodeList document.querySelectorAll() , ,가 .HTMLCollection document.getElementsByClassName().HTMLCollection왜 한쪽 컬렉션을 고치고 다른 한쪽은 고치지 않는지는 전혀 미스터리입니다.그 쓸 수 요.document.querySelectorAll() ES6 께 es esfor/of엣지 엣지 엣지 엣지 엣지 엣지 엣지 엣지 엣지 엣지 엣지 엣지 엣지 엣지 엣지.
두 jsFiddle을 합니다.HTMLCollection ★★★★★★★★★★★★★★★★★」nodeList의 출력을 합니다.
2018년 3월 ES6 4차 업데이트
단위, ""Symbol.iterator되어 있기 에 Safari를 할 수 .for (let item of list) 쪽인가에 document.getElementsByClassName() ★★★★★★★★★★★★★★★★★」document.querySelectorAll().
2018년 4월 ES6 5차 업데이트
보아하니, 재연에 대한 지원인 것 같습니다.HTMLCollectionfor/of입니다.
2018년 11월 ES6 6차 업데이트
Microsoft Edge v18(Fall 2018 Windows Update에 포함)을 사용하면 이제 Edge에서 for/of를 사용하여 HTMLCollection과 NodeList를 모두 반복할 수 있음을 확인할 수 있습니다.
따라서 현재 는 "Native for the " (네이티브지원)를 .for/ofHTML Collection Node List html html 。
하면 안 요.for/in on 에NodeLists or 또는HTMLCollections. However, you can use some s. 단, 다음과 같은 기능을 사용할 수 있습니다.Array.prototype methods, as long as you 메서드, 즉.call() them and pass in the 그것들을 통과시키다NodeList ★★★★★★★★★★★★★★★★★」HTMLCollection as ~하듯이this....
따라서 jfriend00의 루프 대체 수단으로 다음 사항을 고려하십시오.
var list= document.getElementsByClassName("events");
[].forEach.call(list, function(el) {
console.log(el.id);
});
MDN에 관한 이 기술을 다룬 좋은 기사가 있습니다.단, 브라우저 호환성에 관한 경고에 주의해 주십시오.
[...] 호스트 개체를 통과합니다.] 브 젝 오 [예 a] object]: [ passing... a ((트호트...]를 지나간다.
NodeList와 같이 표시됩니다.this메서드: "Native Method")로 합니다.forEach가 모든 하는 것은 되지 않으며 으로 알려져 있습니다가 모든 브라우저에서 동작하는 것은 보증되지 않으며 일부 브라우저에서는 장애가 발생하는 것으로 알려져 있습니다.
for루프
갱신(2014년 8월 30일):머지않아 ES6를 사용할 수 있게 됩니다.of
var list = document.getElementsByClassName("events");
for (const el of list)
console.log(el.id);
최신 버전의 Chrome 및 Firefox에서 이미 지원됩니다.
ES6를 할 수 .[...collection] , 「」Array.from(collection) ,
let someCollection = document.querySelectorAll(someSelector)
[...someCollection].forEach(someFn)
//or
Array.from(collection).forEach(someFn)
예:-
navDoms = document.getElementsByClassName('nav-container');
Array.from(navDoms).forEach(function(navDom){
//implement function operations
});
다음 두 줄을 추가할 수 있습니다.
HTMLCollection.prototype.forEach = Array.prototype.forEach;
NodeList.prototype.forEach = Array.prototype.forEach;
HTML Collection은 getElementsByClassName 및 getElementsByTagName에서 반환됩니다.
NodeList가 querySelector에 의해 반환됩니다.모두
다음과 같이 각각에 대해 수행할 수 있습니다.
var selections = document.getElementsByClassName('myClass');
/* alternative :
var selections = document.querySelectorAll('.myClass');
*/
selections.forEach(function(element, i){
//do your stuffs
});
하여 es6를 탈출할 forIE9 ie ie ie ie ie ie ie ie ie ie ie ie ie ie ie ie ie ie ie 。
ES5 에 2 2, 2 개 es es es es es es es es es es es. '빌린다', '빌린다' 이렇게 할 수 있어요Array의 »forEach에반이 말한 것처럼
하지만 더 좋은 건...
Object.keys()(이것에는,forEach및 필터링을 통해 자동으로 "소유 속성"이 지정됩니다.
즉, 기본적으로는 이 작업을 수행하는 것과 동등합니다.for... in a HasOwnProperty 매끄럽다 더 부드러워요.
var eventNodes = document.getElementsByClassName("events");
Object.keys(eventNodes).forEach(function (key) {
console.log(eventNodes[key].id);
});
★★★의 대체 수단Array.fromArray.prototype.forEach.call
각각: Array.prototype.forEach.call(htmlCollection, i => { console.log(i) });
맵: Array.prototype.map.call(htmlCollection, i => { console.log(i) });
IE 11 및 Firefox 49에서 각각을 사용하는 데 문제가 있었습니다.
이런 해결 방법을 찾았습니다.
Array.prototype.slice.call(document.getElementsByClassName("events")).forEach(function (key) {
console.log(key.id);
}
, 3월 Chrome 49.0에서는for...of works에서 HTMLCollection:
this.headers = this.getElementsByTagName("header");
for (var header of this.headers) {
console.log(header);
}
메뉴얼을 참조해 주세요.
다만, 이 기능은, 다음의 회피책을 적용했을 경우에만 유효합니다.for...of:
HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
로 사용할 필요가 있습니다.for...ofNodeList:
NamedNodeMap.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
기대하다/기대하다for...of아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 맞다.미해결 문제는 다음과 같습니다.
https://bugs.chromium.org/p/chromium/issues/detail?id=401699
업데이트: Expenzor의 코멘트를 참조해 주세요.이것은 2016년 4월 현재 수정되었습니다. HTMLCollection.protype[Symbol.iterator] = Array.protype[Symbol.iterator]를 추가할 필요가 없습니다.HTMLCollection for.../를 사용하여 반복하기 위해
온 엣지
if(!NodeList.prototype.forEach) {
NodeList.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}
항상 사용하는 간단한 회피책
let list = document.getElementsByClassName("events");
let listArr = Array.from(list)
그런 다음 선택 항목에서 원하는 배열 방법을 실행할 수 있습니다.
listArr.map(item => console.log(item.id))
listArr.forEach(item => console.log(item.id))
listArr.reverse()
들어 )를 사용하는 의 older older(ES5)를 사용할 수 .as any:
for (let element of elementsToIterate as any) {
console.log(element);
}
다음과 같이 할 수도 있습니다.
let elements = document.getElementsByClassName("classname");
for(let index in elements) {
if(index <= elements.length) {
console.log(elements[index]);
}
}
let elements = document.getElementsByClassName("classname");
for (let index in elements) {
if (index <= elements.length) {
console.log(elements[index]);
}
}
<div class="classname"> element 1 </div>
<div class="classname"> element 2 </div>
<div class="classname"> element 3 </div>
또는
let elements = document.getElementsByClassName("classname");
for(let ele of elements) {
console.log(ele);
}
let elements = document.getElementsByClassName("classname");
for (let ele of elements) {
console.log(ele);
}
<div class="classname"> element 1 </div>
<div class="classname"> element 2 </div>
<div class="classname"> element 3 </div>
<div class="classname"> element 4 </div>
변경하다
var list= document.getElementsByClassName("events");
console.log(list[0].id); //first console output
for (key in list){
console.log(list[key].id); //second console output
}
언급URL : https://stackoverflow.com/questions/22754315/for-loop-for-htmlcollection-elements
'source' 카테고리의 다른 글
| Node.js에서 HTTPS 서버를 작성하는 방법 (0) | 2023.02.04 |
|---|---|
| 다른 스레드가 완료되었는지 확인하는 방법 (0) | 2023.02.04 |
| Fedora 19 명령줄에서 데이터베이스 다이어그램을 생성하려면 어떻게 해야 합니까? (0) | 2023.02.04 |
| PHP 변수에서 공백 공간을 제거하는 방법은 무엇입니까? (0) | 2023.02.04 |
| query_cache_size, Qcache_total_blocks 및 query_alloc_block_size (0) | 2023.02.04 |