码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-09-10 13:05:59      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

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获得的不是数组的问题!

标签:

原文地址:http://www.cnblogs.com/jlzt/p/5859081.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!