最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Removing elements from an array: pop is not a function (javascript) - Stack Overflow

programmeradmin2浏览0评论
thead = new Array();
alert(thead.length);
thead = document.getElementsByTagName("th");
alert(thead.length);


thead.pop();
alert(thead.length);

document.getElementsByTagName("th") returns an array of elements, so thead variable should be an array, if so, then why it gives me the error "thead.pop() is not a function"?

thead = new Array();
alert(thead.length);
thead = document.getElementsByTagName("th");
alert(thead.length);


thead.pop();
alert(thead.length);

document.getElementsByTagName("th") returns an array of elements, so thead variable should be an array, if so, then why it gives me the error "thead.pop() is not a function"?

Share Improve this question edited Aug 26, 2019 at 10:11 Vadim Kotov 8,2848 gold badges50 silver badges63 bronze badges asked Jul 5, 2012 at 16:14 AikanároAikanáro 8493 gold badges20 silver badges44 bronze badges 1
  • Are you trying to remove from the DOM, or just from the list? If you actually want it removed from the DOM, do this... var last = thead[thead.length - 1]; last.parentNode.removeChild(last); The element will be removed from the DOM, as well as the thead list. – user1106925 Commented Jul 5, 2012 at 16:24
Add a ment  | 

3 Answers 3

Reset to default 7

getElementsByTagName (docs) does not return an Array, it returns a NodeList. As said by the linked NodeList docs:

NodeList are used very much like arrays and it would be tempting to use Array.prototype methods on them. This is, however, impossible.

There are some Array like things you can do with a NodeList, and you can even .apply some Array.prototype methods to them, but you should read the docs to avoid the "gotchas", especially where problems with the NodeList being "live" could bite you.

getElementsByTagName() returns a DOM 2 NodeList, not an Array.

Technically, document.getElementsByTagName returns a NodeList object, which has no pop function.

Try alert(Array.isArray(thead)), and you'll see that it returns false

发布评论

评论列表(0)

  1. 暂无评论