如何从HTMLCollection中删除项目?

时间:2016-05-18 22:17:36

标签: javascript htmlcollection

我有一些Javascript代码可以从HTMLCollection中删除项目,如下面的代码所示。调用splice时出现错误:allInputs.splice is not a function。如果元素类型不是按钮类型,我需要从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
        }
    }

5 个答案:

答案 0 :(得分:8)

您需要将其从DOM中删除,因此请替换:

allInputs.splice(i, 1);

使用:

allInputs[i].parentNode.removeChild(allInputs[i])

即使是像IE 6这样的古老浏览器也能兼容。该集合将自动更新。反向迭代集合是一个好主意,因为每次删除成员时,它都会变短。

请注意:

[].slice.call(allInputs)

将在IE8等浏览器中失败,这些浏览器不允许主机对象在内置方法中 this

答案 1 :(得分:7)

HTMLCollection是一个类似于实时数组的对象,这意味着如果您需要从此类集合中删除元素,则必须将其从DOM中删除。您始终可以将其克隆到数组中进行操作。

答案 2 :(得分:1)

要从HTMLCollection 图片中删除新创建的 img ,我会使用下一个字符串

img.ownerDocument.images[img.index].remove()

img.index 在创作时定义

答案 3 :(得分:0)

你也可以使用数组的splice方法,并且知道集合的length属性是只读的,所以你必须在拼接之前明确地使它成为可写的:

Object.defineProperty(allInputs, 'length', {
 writable: 'true'
});
Array.prototype.splice.call(allInputs, i, 1);

答案 4 :(得分:0)

实际上可以做到这一点,您只需要将所需的元素推送到另一个HTMLCollection中,然后将原始集合设置为新集合(或仅使用新集合)即可即可。

var allInputs = contentElement.getElementsByTagName('input');
var inputsWeActuallyWant = [];
for (var i = (allInputs.length - 1) ; i >= 0; i--) {
    if (allInputs[i].type === "button") {
        inputsWeActuallyWant.push(allInputs[i]);
    }
}
allInputs = inputsWeActuallyWant;
相关问题