Ankesh Ankesh - 24 days ago 7
Javascript Question

Why I am getting "cannot read property style of null" error?

I am not able to understand why it is giving


uncaught typeError: Cannot read property 'style' of null" at line 38


when I am moving the mouse pointer at all the divs. Every time I move the pointer at a div, I get the error.

Please explain what is the issue.



var top = "p3";

function toTop(newTop) {
var domTop = document.getElementById(top).style;
var domNew = document.getElementById(newTop).style;
domTop.zIndex = "0";
domNew.zIndex = "10";
top = document.getElementById(newTop).id;
}

.para1 {
position: absolute;
top: 10;
left: 120;
z-index: 0;
border: solid;
padding: 80;
width: 300;
background-color: aqua;
}
.para2 {
position: absolute;
top: 50;
left: 150;
z-index: 0;
border: solid;
padding: 80;
width: 300;
background-color: yellow;
}
.para3 {
position: absolute;
top: 100;
left: 180;
z-index: 0;
border: solid;
padding: 80;
width: 300;
background-color: red;
}

<div style="z-index: 10;" class="para1" id="p1" onmouseover="toTop('p1')">Frame One</div>
<div style="z-index: 5;" class="para2" id="p2" onmouseover="toTop('p2')">Frame Two</div>
<div style="z-index: 0;" class="para3" id="p3" onmouseover="toTop('p3')">Frame Three</div>




Answer

You need to rename the readonly var top to for example myTop - it gives errors since window.top is the handle for the main window

var myTop = "p3";

function toTop(newTop) {
  var domTop = document.getElementById(myTop).style;
  var domNew = document.getElementById(newTop).style;
  domTop.zIndex = "0";
  domNew.zIndex = "10";
  myTop = document.getElementById(newTop).id;
}

I could not find top to be reserved in the official documentation but it does belong to the list of words to avoid since it is readonly in the browser implementations.