我有一些Javascript代码,可以从HTMLCollection中删除一个项目,如下所示。当调用splice时,会出现错误,提示“allInputs.splice不是一个函数”。如果元素类型不是按钮类型,我需要从HTMLCollection中删除项目。
问题:如何从这样的集合中删除一个项目?
我可以将未删除的项目转移到一个数组中,然后使用该数组而不是原始HTMLCollection,但不确定是否有其他更短的方法来完成此操作。
Javascript代码
var allInputs = contentElement.getElementsByTagName('input');
for (var i = (allInputs.length - 1) ; i >= 0; i--) {
if (allInputs[i].type !== "button") {
allInputs.splice(i, 1);//this is throwing an error since splice is not defined
}
}
splice
方法,除非你实际上将元素从 DOM 中删除或添加到其中,否则无法添加或删除元素。你可能希望将其转换为数组。 - adeneosplice()
),请将集合转换为数组;例如使用array.from(allInputs)
。 - David ThomasArray.prototype
。 - adeneo