首页 > 代码库 > 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获得的不是数组的问题!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。