用JS从动态元素中获取ID
我创建了一个动态列表,每个元素都有自己的ID,但是当我必须使用document.getElementById从javaScript获取它时,会抛出错误(无法设置null的属性(设置'innerhtml'))我该如何求解?
元素ID是正确创建的。 < li id =“ item1”> item1</li>
//This is how I add a new element:
var counter = 1;
function addElement(){
var list = document.getElementById("list");
list.innerHTML += `<li id="item${counter}">item${counter}</li>`;
}
//This function is called when the button is clicked.
//This function is called when the bottom for editing is clicked:
function changeTxt(){
document.getElementById("changeID").innerHTML = document.getElementById("textChange").value;
}
//ChangeID is a variable saved in another function.
I created a dynamic list, each element has its own id but when I have to get it from javascript with document.getElementById an error is thrown (Cannot set properties of null (setting 'innerHTML')) how can I solve?
The element id are created correctly. <li id="item1">item1</li>
//This is how I add a new element:
var counter = 1;
function addElement(){
var list = document.getElementById("list");
list.innerHTML += `<li id="item${counter}">item${counter}</li>`;
}
//This function is called when the button is clicked.
//This function is called when the bottom for editing is clicked:
function changeTxt(){
document.getElementById("changeID").innerHTML = document.getElementById("textChange").value;
}
//ChangeID is a variable saved in another function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能是因为您没有引用ID。
我认为您的元素看起来像这样的rn:
&lt; li id = item64&gt; item64&lt;/li&gt;
,它必须看起来像这样:
&lt; li id =“ item64”&gt; item64&ltt ;/li&gt;
It might be because you didn't quoted the ID.
I think your element look like this rn :
<li id=item64>item64</li>
and it must look like this instead :
<li id="item64">item64</li>
尝试将
+=
添加到分配中,以不替换列表内容,而是添加到其中。否则,您只有一个列表中的一个元素,这是最后一个计数器值。如果它不起作用,请使用Indept工具检查是否正确创建了元素;)
Try adding
+=
to your assignment, to not replace the list contents, but add to it. Otherwise you will only have one element in the list, which is the last counter value.If it doesn't work, use inpect tool to check if elements were created correctly ;)