Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Javascript object to dom element

Tags:

javascript

dom

I've had this confusion since long. There is an error called cannot read property of null on chrome inspector.

Upon searching and reading, i found that a property (eg style) can be applied to a DOM element, but if it is rendered as a javascript object it gives the above error.

So how do i go about this?

<html>
    <head>
        <style>
            #test {background:black;width:30px;height:30px;}
        </style>
        <script>
            var a = document.getElementById('test');
            a.style.background = "#f00";
        </script>
    </head>
    <body>
            <div id="test">
            </div>
</body>
</html>

When i did alert(typeof a); it gives as object. So how do I, in general, change properties of elements ??

like image 653
Aaditi Sharma Avatar asked Jan 26 '26 05:01

Aaditi Sharma


2 Answers

The issue is that #test doesn't exist when the script is executed. The script is executed immediately as the page is loaded, and at the point when the browser executes the script, it hasn't gotten to <div id="text"></div>, so document.getElementById('test') returns null.

null values don't have properties, so calling: a.style.background... causes JavaScript to error out. If you'd attached this script to body.onload, the callback function provided would execute after the rest of the page was loaded:

document.body.onload = function(){
  var a = document.getElementById('test');
  if ( a ) //just a check to make sure that `a` was set so that it doesn't error again.
  {
    a.style.background = "#f00";
  }
};
like image 50
zzzzBov Avatar answered Jan 28 '26 20:01

zzzzBov


Your javascript is running before the page has finished loading.

You need to put your javascript inside an window.onload like this:

window.onload = function()
{
  var a = document.getElementById('test');
  a.style.background = "#f00";
}
like image 37
psx Avatar answered Jan 28 '26 18:01

psx