Set id to newly created elements Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Set id to newly created elements without wasting too much if your time.

The question is published on by Tutorial Guruji team.

This is mine first question, I’m glad to be part of this community.

Like I said in the title. I want to set ID to newly created elements. I don’t know what I’m doing incorrectly.

This is mine code sample:

function DataBack(response) {
var ci_output = document.getElementById('ci_output');
data = JSON.parse(response);
for (i = 0; i < data.result.length; i++) {
    var li = document.createElement("p");
    li.setAttribute("id",'cmdbitem' + i);
    li.setAttribute('onclick', 'displayDetails(data.result[' + i + '])');
    document.getElementById('cmdbitem' + i).onclick = changeColor; //this function is throwing error "Uncaught TypeError: document.getElementById(...) is null"
    li.innerHTML = data.result[i].name;

What i want to achieve is to change color for newly created item which user click on. For this i need ID. I made test and ID is set because e.g. this specific element is behave like it should

#cmdbitem2 {
cursor : pointer;


Why this document.getElementById(‘cmdbitem’ + i).onclick = changeColor; is throwing an error ?

Thanks from advance.


because the new element li is not inserted to document yet (which happends at ci_output.appendChild(li);).

but you can simply use li here, no need to get it though getElementById

Here is a complete example from your code.

for (let i = 0; i < data.result.length; i++) {
   let li = document.createElement("p") = 'cmdbitem' + i
   li.addEventListener('click', ()=>displayDetails(data.result[i]))
   li.addEventListener('click', changeColor)
   li.innerHTML = data.result[i].name

some reference:

  • arrow function (you can also use normal function)
  • let (Always use let instead of var)
We are here to answer your question about Set id to newly created elements - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji