Why JavaScript cant find given InnerHTML and returs Cannot set property 'innerHTML' of null?

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?

Answers


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.


Need Your Help

How to store Twitter status id_str in mysql database

php mysql twitter

I'm scraping popular tweets from twitter search api. For each tweet scraped, I log the status variable "id_str" and check against it prior to every scrape to ensure there are no duplicates added to...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.