[英]Access and remove dynamically created element
我使用 for 循环创建了一堆具有唯一 ID 的图像。 它们看起来像这样:
<img src="image.jpg" id="110021002" />
<img src="image.jpg" id="110021003" />
<img src="image.jpg" id="110031002" />
...
稍后在代码中,我想通过 ID 选择其中一张图像并将其删除。 我尝试了以下方法:
var removeId = '110021002';
var img = document.getElementById(removeId);
img.parentNode.removeChild(img);
但我收到以下错误:
Cannot read property 'parentNode' of null
不太确定这里发生了什么。 是因为图像是动态创建的吗?
您的代码完美运行: http ://jsbin.com/zexoweyu/3/edit第一次删除元素,显然在第二次尝试时该元素不存在,它将抛出给定的错误。
在小提琴上:
是的,id 可以以数字开头。
**Attribute ID** Specifies a unique id for the element. Naming rules:
Must contain at least one character
Must not contain any space characters
In HTML, all values are case-insensitive
您不能拥有以数字开头的ID。 尝试在它们前面加上一个字母。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.