Home > Article > Web Front-end > Explanation of the difference between JavaScript data element collection and array_javascript skills
The getElementsByName(name) method is to obtain all elements with the name attribute in the page, but the content obtained by this method is different in IE and standard browsers. In IE, the elements obtained by the getElementsByName(name) method have their own name attribute, that is, all the elements listed in the form (these elements themselves have their own name attribute); in standard browsers, getElementsByName The element obtained by the (name) method is an element with the name attribute (it already has this attribute and this attribute is artificially added). So if you use this method to get all the elements with name in the page in IE browser, you can only get out those elements that already have this attribute (form class elements), but those artificially added name attribute elements will not. will be taken out; the standard browser will not do this, it will take out all elements with the name attribute in the page.
What the getElementsByName() and getElementsByTagName() methods have in common is that they will form the obtained page elements into a collection of elements, not an array (although it is an array when printed using console.log() in firebug form). If you use the Object.porototype.toString.apply(arr) method to view the obtained data results, it returns "[object HTMLCollection]" instead of "[object Array]". In this way, the element collection obtained by these two methods cannot be used to call some methods of the array to operate like an array. Instead, this collection needs to be converted. Converting the element collection into an array form can be operated like an array. The elements inside are processed.
This element collection has the following attributes and methods:
1. Element index (index)
2. The length of the element collection (length)
3. item() method: The corresponding elements in the collection can be obtained by passing in different index values. There is no such method under IE.
4. There is also a namedItem(name) method in FF to obtain the first element with the name attribute. This method is only available under FF.
There are many ways to convert a collection of elements into an array form. You can search on the Internet to find many methods. You can also learn a lesson from Situ Zhengmei's blog post "JS Converts Array-like Objects into Array Objects".
The following is an array conversion method: