[Solved] JS code not working because of bad placement


if you want to run a javascript code on finish loading, a best practice is to make a function that is called in the onload method.

HTML Code

<body onload="changediv('2');">
    <div id="1">11111111111 1111111111111 111111111</div>
    <div id="2">222222c   2222222222222 22222222</div>
    <div id="3">23333333 3 333 3 3 3 3 3 33333 3</div>
    <div id="4">4444 4  4 44444 4 4 4 4444 </div>
</body>

Javascript function

function changediv(id){
    var d = document.getElementById(id);
        d.style.color = "#ccc";
}

here you have an example on JSBIN

http://jsbin.com/ajawic/1/edit

In this way, you ensure that the object exists before use.

solved JS code not working because of bad placement