Home > database >  get id from dynamic element with js
get id from dynamic element with js

Time:07-07

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.

CodePudding user response:

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>

CodePudding user response:

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

  • Related