MR KHAN COMUTI Leader MR KHAN COMUTI Leader - 27 days ago 10
Javascript Question

How can I change the colour of an element I have created using javascript

I am trying to change the colour of an element I have created using JavaScript. The information in this element is populated from data in a database.

var done = orders[i][2];
var id = orders[i][0];
id_and_name = JSON.stringify(id_and_name);
content = content + "<div onClick='loadOrder("+id_and_name+")' class='btn btn-lg btn-info'
id= '"+id+"'><span class='glyphicon glyphicon-shopping-cart'></span>
ID: "+orders[i][0]+"</br>Name: " + orders[i][1]+"</div>";
if (done == 0){
alert("order not done");
document.getElementById(id).style.color = "red";
alert(id);
}else{
alert("order done");
document.getElementById(id).style.color = "green";
alert(id);
}

document.getElementById("main_content").innerHTML = content;


The code works without syntax errors when I remove the document.getElementById lines and runs through the appropriate branch. When I include these lines, I get a syntax error : VM882:125 Uncaught TypeError: Cannot read property 'style' of null(…).

Can I not change the colour of elements that I have created using javascript in this way. If not why?, and what method should I be using.

I have also checked what the value of id is with alert(id) and they are fine. Both are strings e.g.: "43" and "44". I have also tried to replace document.getElementById(id).style.color = "red"; with document.getElementById("43").style.color = "red"; and I get the same error. When I remove the line the elements are created with the correct ID but of course i cannot change the colour then.

Answer

You have not inserted the element into the DOM yet, and as such you can't get it with getElementById.

This would go a lot easier if you actually create real elements, and not just strings

var done  = orders[i][2];
var id    = orders[i][0];
var id_and_name = JSON.stringify(id_and_name);
var div   = document.createElement('div');
var span  = document.createElement('span');
var text1 = document.createTextNode('ID: ' + orders[i][0]);
var text2 = document.createTextNode('Name: ' + orders[i][1]);
var br    = document.createElement('br');
var main  = document.getElementById("main_content");

div.className = 'btn btn-lg btn-info';
div.id = id;
div.addEventListener('click', function() {
    loadOrder(id_and_name);
},false);

span.className = 'glyphicon glyphicon-shopping-cart';

if (done == 0) {
    div.style.color = "red";
} else {
    div.style.color = "green";
}

// later, insert the elements in the DOM

main.appendChild(div);
main.appendChild(span);
main.appendChild(text1);
main.appendChild(br);
main.appendChild(text2);
Comments