Как перебрать htmlcollection в js
Цикл For для элементов HTMLCollection
Я пытаюсь установить get id всех элементов в HTMLCollection. Я написал следующий код:
но я получил следующий вывод в консоли:
10 ответов
Еээк. Вы не должны перебирать nodeList или HTMLCollection С for/in и когда вы делаете итерации, вы должны на самом деле получить значение из списка, используя индекс в вашей итерации.
в ES5 (и совместим с чем-либо после него) вы можете повторять так:
for/in предназначен для итерации свойств объекта. Он не предназначен для перебора массива или массивоподобного объекта, которым является уход. Я просто попробовал это в Хром и выполняя его так, как вы были переборе он будет извлекать элементы в списке (индексы 0, 1, 2, и т. д. ), но также получит length и item свойства. The for/in итерация просто не будет работать для HTMLCollection.
в Firefox, ваш for/in итерация вернет эти элементы (все iterable свойства объекта):
обновление для ES6 в 2015
добавлено в ES6 Array.from() это преобразует структуру, подобную массиву, в фактический массив. Это позволяет перечислять список прямо так:
рабочая демонстрация (в Firefox, Chrome и Edge как апреля 2016 года): https://jsfiddle.net/jfriend00/8ar4xn2s/
обновление для ES6 в 2016
теперь вы можете использовать ES6 для / конструкции с NodeList и HTMLCollection просто добавив это в свой код:
тогда вы можете сделать:
это работает в текущей версии Chrome, Firefox и Edge.
второе обновление для ES6 в декабре 2016
по состоянию на декабрь 2016 года, Symbol.iterator поддержка была встроена в Chrome v54 и Firefox v50, поэтому приведенный ниже код работает сам по себе. Он еще не встроен в Edge.
третье обновление для ES6 в декабре 2017
я также обновил вышеуказанный jsFiddle, чтобы он тестировал оба!—7—> и nodeList отдельно и захватывает вывод в самом jsFiddle.
четвертое обновление для ES6 в марте 2018
пятое обновление для ES6 в апреле 2018
по-видимому, поддержка итерации HTMLCollection С for/of будет приходить к краю 18 осенью 2018 года.
поэтому рассмотрим следующее в качестве альтернативы jfriend00 в for цикл:
хороший статья о MDN это охватывает эту технику. Обратите внимание на их предупреждение о совместимости браузера, хотя:
[. ] передача объекта хоста (например, NodeList ) как this для собственного метода (например, forEach ) не гарантируется работа в во всех браузерах и не работает в некоторых.
итак, пока этот подход удобен, a for петли могут быть самые браузерные решения.
он уже поддерживается в последних версиях Chrome и Firefox.
How to Loop Through an HTMLCollection
If you’ve ever written a frontend application in JavaScript, you’ve probably run into HTMLCollections.
I recently deployed Plant Flashcards, a full-stack application where you can learn about plant facts and test your knowledge. I used a vanilla JavaScript for the frontend and a homegrown Rails API for the backend! Interacting with JSON objects and trying to manipulate elements on the DOM made me realize that HTMLCollections were very different from plain ole, regular Arrays.
HTMLCollections are array-like objects that return HTML elements on the DOM. Unlike regular Arrays, they’re “live” objects, so they’ll change automatically depending on the contents of the DOM.
Let’s dive in
And here’s what plantsArray might look like when logged to the console:
The difference between HTMLCollections and Arrays
Out of all the CRUD (Create, Read, Update, Delete) operations, HTMLCollections are mainly used for reading elements. They’re not meant for DOM manipulation because they’re live objects. Arrays, on the other hand, can be easily mutated.
HTMLCollections also have different built-in properties and methods than Arrays.
See what happens when we try to access the individual elements in an HTMLCollection like we would with an Array.
How to loop through an HTMLCollection
Conclusion
Get comfortable interacting with HTMLCollections and their unique properties and methods!
For loop for HTMLCollection elements
But I got the following output in console:
13 Answers 13
Summary (added in Dec 2018)
Do not ever use for/in to iterate a nodeList or an HTMLCollection. The reasons to avoid it are described below.
To include older browsers (including things like IE), this will work everywhere:
Explanation For Why You Should Not Use for/in
for/in is meant for iterating the properties of an object. That means it will return all iterable properties of an object. While it may appear to work for an array (returning array elements or pseudo-array elements), it can also return other properties of the object that are not what you are expecting from the array-like elements. And, guess what, an HTMLCollection or nodeList object can both have other properties that will be returned with a for/in iteration. I just tried this in Chrome and iterating it the way you were iterating it will retrieve the items in the list (indexes 0, 1, 2, etc. ), but also will retrieve the length and item properties. The for/in iteration simply won’t work for an HTMLCollection.
In Firefox, your for/in iteration would return these items (all the iterable properties of the object):
Evolution of Browser Support for NodeList and HTMLCollection iteration
Following below is an evolution of how browsers have evolved through the time period 2015-2018 giving you additional ways to iterate. None of these are now needed in modern browsers since you can use the options described above.
Update for ES6 in 2015
Added to ES6 is Array.from() that will convert an array-like structure to an actual array. That allows one to enumerate a list directly like this:
Working demo (in Firefox, Chrome, and Edge as of April 2016): https://jsfiddle.net/jfriend00/8ar4xn2s/
Update for ES6 in 2016
You can now use the ES6 for/of construct with a NodeList and an HTMLCollection by just adding this to your code:
This works in the current version of Chrome, Firefox, and Edge. This works because it attaches the Array iterator to both the NodeList and HTMLCollection prototypes so that when for/of iterates them, it uses the Array iterator to iterate them.
Second Update for ES6 in Dec 2016
As of Dec 2016, Symbol.iterator support has been built-in to Chrome v54 and Firefox v50 so the code below works by itself. It is not yet built-in for Edge.
Third Update for ES6 in Dec 2017
I’ve also updated the above jsFiddle so it tests both HTMLCollection and nodeList separately and captures the output in the jsFiddle itself.
Fourth Update for ES6 in Mar 2018
Fifth Update for ES6 in Apr 2018
Apparently, support for iterating an HTMLCollection with for/of will be coming to Edge 18 in Fall 2018.
Sixth Update for ES6 in Nov 2018
I can confirm that with Microsoft Edge v18 (that is included in the Fall 2018 Windows Update), you can now iterate both an HTMLCollection and a NodeList with for/of in Edge.
So, now all modern browsers contain native support for for/of iteration of both the HTMLCollection and NodeList objects.
Живые и неживые коллекции в JavaScript
HTMLCollection — коллекция непосредственно HTML-элементов.
NodeList — коллекция узлов, более абстрактное понятие. Например, в DOM-дереве есть не только узлы-элементы, но также текстовые узлы, узлы-комментарии и другие, поэтому NodeList может содержать другие типы узлов.
При работе с DOM-элементами в нашем случае тип коллекции значительной роли не играет, поэтому для удобства будем рассматривать их как одну сущность — коллекцию.
Во время работы с коллекциями можно столкнуться с поведением, которое покажется странным, если не знать один нюанс — они бывают живыми (динамическими) и неживыми (статическими). То есть либо реагируют на любое изменение DOM, либо нет. Вид коллекции зависит от способа, с помощью которого она получена. Рассмотрим на примере.
Разница между живыми и неживыми коллекциями
Допустим, в разметке есть список книг:
Для взаимодействия с книгами получим с помощью JavaScript список всех нужных элементов. Чтобы в дальнейшем увидеть разницу между видами коллекций, используем разные способы поиска элементов — свойство children и метод querySelectorAll :
Пока никакой разницы не видно. В обоих случаях console.log выведет одни и те же элементы. Но что, если попробовать удалить из DOM одну из книг?
Другие способы получить коллекцию
Кроме children и querySelectorAll есть другие способы поиска DOM-элементов:
getElementsByTagName(tag) — находит все элементы с заданным тегом,
getElementsByClassName(className) — находит все элементы с заданным классом,
Как использовать
Для решения большинства задач можно ограничиться неживыми коллекциями. Но если нужно сохранить ссылку на реальное состояние DOM — понадобится живая коллекция. Это удобно в тех случаях, когда программе нужно постоянно манипулировать списком элементов, которые могут регулярно удаляться и добавляться. Хороший пример — задачи в таск-трекере. С помощью живой коллекции можно хранить именно те задачи, которые фактически существуют в данный момент времени.
При этом нужно помнить — массив статичен, поэтому при таком преобразовании теряются преимущества живых коллекций.
How do you get elements from a javascript HTMLCollection
I can’t understand why I cant get elements from a HtmlCollection. This code example:
produces this output on console:
I’m trying to get the dic.jcrop-holder object but i cant get it from my variable col. None of this works:
So if the length is 0 why does the console show a length of 1, as well as objects inside? When I open the node it contains children. What’s going on?
Here are some expanded nodes. I didn’t expand div.jcrop.holder because it is too long. Here are children elements:
3 Answers 3
The problem is you have placed the script in the header which gets executed before the html elements are loaded, so getElementsByClassName() will not return any elements.
One solution is to wait for the html elements to be loaded then execute your script, for that you can use the window objects load event
Or you can place your script at the bottom of the body element instead of in head so that by the time the script is parsed and executed the elements are loaded in the dom
I was facing the same issue and the solution to this problem was to place my script in the end of the document, in order to wait to the whole document to be loaded before start changing or selecting the HTMLCollection elements. Hope it helps.
look this code, with it you can use a class attribute for a HTMLColletion
Not the answer you’re looking for? Browse other questions tagged javascript or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.22.41046
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.




