用JS从动态元素中获取ID

发布于 2025-02-13 15:32:53 字数 782 浏览 1 评论 0原文

我创建了一个动态列表,每个元素都有自己的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

離殇 2025-02-20 15:32:53

可能是因为您没有引用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>

套路撩心 2025-02-20 15:32:53

尝试将+=添加到分配中,以不替换列表内容,而是添加到其中。否则,您只有一个列表中的一个元素,这是最后一个计数器值。

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>

如果它不起作用,请使用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.

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 ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文