Brett
Brett

Reputation: 558

Cannot read property 'parentNode'

I'm beginning to learn javascript, and I can't figure out for the life of me, why this 'Cannot read property 'parentNode'' is getting thrown in the console; and why the for loop is calling an after the third link.

I was following a lesson on javascript rollovers, the rollover works, but why is the error being thrown?

<style type="text/css" media="screen">
  #caption, #content {
    width: 30%;
    float: left;
    padding: 10%;
    line-height: 1.675em;
  }
</style>

<script type="text/javascript" charset="utf-8">
  window.onload = initRollover;

  function initRollover() {
    for (var i = 0; i < document.links.length; i++) {  
      console.log(i);  
      if(document.images[i].parentNode.tagName == "A") {
        setupRollover(document.images[i]);
      } 
      document.links[i].setAttribute('class', 'test');
    }
  }

  function setupRollover(thisImage){
    thisImage.outImage = new Image();
    thisImage.outImage.src = thisImage.src;
    thisImage.onmouseout = function() {
      this.src = this.outImage.src;
    }

    thisImage.overImage = new Image();
    thisImage.overImage.src = "images/" + "silver" + ".jpg";
    thisImage.onmouseover = function(){
      this.src = this.overImage.src;
    }
  }
</script>

<div id="content" style="background: lightgreen;">
  <img src="images/silver.jpg" width="240" alt="Silver" id="photoA">
  <br><br>
  <a href="boom.html">
    <img src="images/gold.jpg" width="240" alt="Gold" id="photoB">
  </a>
</div>
<div id="caption">
  <a href="foo.html">Lorem ipsum dolor sit amet,</a> consectetur adipisicing elit, sed do eiusmod
  tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
  quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
  consequat. <a href="bar.html">Duis aute irure dolor </a>in reprehenderit in voluptate velit esse
  cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
  proident, sunt in <a href="car.html">culpa qui officia deserunt</a> mollit anim id est laborum.
</div>
<div style="clear:both"></div>

Thanks

Upvotes: 0

Views: 1659

Answers (1)

Kishore Venkateshan
Kishore Venkateshan

Reputation: 31

I am not entirely sure as to what you are trying to achieve. But the problem i see is here

function initRollover() {
for (var i = 0; i < document.links.length; i++) {  
  console.log(i);  
  if(document.images[i].parentNode.tagName == "A") {
    setupRollover(document.images[i]);
  } 
  document.links[i].setAttribute('class', 'test');
}
}

In you html code, there are 3 links with tags but only 2 images with tag. So when i = 2, there is no document.images[2]. Hence the parentNode is null. That leads to your error.

Hope that helped.

Upvotes: 1

Related Questions