首页 > 代码库 > getElementsByTagName获得的不是数组的问题!

getElementsByTagName获得的不是数组的问题!

getElementsByTag() returns a NodeList instead of an Array. You can convert a NodeList to an Array but note that the array will be another object, so reversing it will not affect the DOM nodes position.

var listNodes = document.getElementById("myDivHolderId").getElementsByTagName("img");var arrayNodes = Array.slice.call(listNodes, 0);arrayNodes.reverse();

In order to change the position, you will have to remove the DOM nodes and add them all again at the right position.

Array.prototype.slice.call(arrayLike, 0) is a great way to convert an array-like to an array, but if you are using a JavaScript library, it may actually provide a even better/faster way to do it. For example, jQuery has $.makeArray(arrayLike).

You can also use the Array methods directly on the NodeList:

Array.prototype.reverse.call(listNodes);

总之意思就是使用我们的getElement获得的是一个nodeList,不是组数,想要使用还要转换!!!

getElementsByTagName获得的不是数组的问题!