1

Why site http://xn--wiadomesny-37b.pl/test/ throws Uncaught TypeError: Cannot set property 'innerHTML' of null?

HTML (http://xn--wiadomesny-37b.pl/test/):

<div class="castle_array" id="2x1" name="2x1"></div>
<div class="castle_array" id="3x1" name="3x1"></div>
<div class="castle_array" id="4x1" name="4x1"></div>
...

JavaScript (http://xn--wiadomesny-37b.pl/test/B_modeWindow.js):

for (x = 1; x <= 5; x++) {
for (y = 1; y <= 5; y++) {
  document.getElementById(x+"x"+y).addEventListener("click",B_modeWindow('1',this.id));
}}

When I alter

("click",B_modeWindow('1',this.id)

to

("click",B_modeWindow('1','string')

it works like a charm - why?

1
  • Because the JavaScript isn't finding the element on which it should, apparently, be working. Please post a live demo that reproduces the, or your, problem. Commented Sep 9, 2012 at 19:00

1 Answer 1

2

There are two fundamental issues with your code.

First, when you do addEventListener("click", B_modeWindow('1', this.id));, you're not assigning the B_modewindow callback to the click event handler, you are actually executing the function.

Secondly, in that context this does not refer to the clicked element, it refers to the Window object, thus this.id gives you undefined, use event.target.id instead:

To fix it, use the following instead:

var el = document.getElementById(x+"x"+y);
el.addEventListener("click", function (event) {
  B_modeWindow('1', event.target.id);
});

Here's a simplified DEMO.

Sign up to request clarification or add additional context in comments.

3 Comments

Yet it thorws (not critical) error: Uncaught TypeError: Cannot set property 'innerHTML' of null B_modeWindow.js:14 B_modeWindow.xmlhttp.onreadystatechange
@user1656447: Have you updated your code with mine? See my demo, the alerted value is correct. Can you update your site, so that I can check what's wrong?
Sorry Joao Silva, your solution works perfect. Thank you for very detailed and helpful explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.