简体   繁体   English

用js从动态元素中获取id

[英]get id from dynamic element with js

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?我创建了一个动态列表,每个元素都有自己的 id,但是当我必须使用 document.getElementById 从 javascript 中获取它时,会引发错误(无法设置 null 属性(设置'innerHTML'))我该如何解决?

The element id are created correctly.元素 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.

It might be because you didn't quoted the ID.可能是因为您没有引用 ID。

I think your element look like this rn : <li id=item64>item64</li>我认为您的元素看起来像这样 rn: <li id=item64>item64</li>

and it must look like this instead : <li id="item64">item64</li>它必须看起来像这样: <li id="item64">item64</li>

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.否则,列表中将只有一个元素,即最后一个计数器值。

 const list = document.getElementById('list'); for (let counter = 1; counter < 4; ++counter) { list.innerHTML += `<li id="item${counter}">item${counter}</li>`; } console.log(document.getElementById("item3"));
 <ul id="list"></ul>

If it doesn't work, use inpect tool to check if elements were created correctly ;)如果它不起作用,请使用检查工具检查元素是否正确创建;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM