0

I've made this function that gives the error

Cannot read property 'style' of null

Can you please help me figure out what the problem is?

function cade()
{
    var a = document.getElementById(this.id).style.top;
    a = a + 100;
    document.getElementById(this.id).style.top =  a+'px';
}
cade.call(document.getElementById("p"));
DontVoteMeDown
  • 19,660
  • 10
  • 65
  • 96
details
  • 13
  • 4
  • 1
    document.getElementById(this.id) is returning null – Ryan May 11 '15 at 14:00
  • I have the div with the 'p' id. Why could this be invalid? – details May 11 '15 at 14:02
  • Inside the function what does `console.log(this)` return? If it's `null` (as it seems likely to be) you probably need to read this question and its accepted answer: http://stackoverflow.com/q/14028959/82548 – David says reinstate Monica May 11 '15 at 14:09
  • Can you include the relevant HTML and any CSS that may apply to it? I suspect this is related to missing style rules causing the `top` not to be applied, rather than problems with the ID or execution order. – ssube May 11 '15 at 14:21

1 Answers1

0

While your function works correctly, the styling on that element prevents you from doing much to move it. Adding position: absolute or something along those lines will make it move correctly.

Since you're passing the element as this, you don't need to fetch it again using getElementById. The reference you have is already perfectly valid, so you can simplify the code like:

function cade() {
  var a = this.style.top;
  a = a + 100;
  this.style.top = a + 'px';
}
cade.call(document.getElementById("p"));
div#p {
  position: absolute;
}
<div id="p">This is some text.</div>
ssube
  • 41,733
  • 6
  • 90
  • 131