I have a for loop that creates div-elements with IDs like 'category1', 'category2' etc. The loop goes through a key/value array, which looks something like this:
"0" : "Java",
"1" : "JavaScript",
"2" : "HTML"
So, the IDs of the divs are 'category' + the key.
Within the for-loop where the elements are added to the innerHTML of a container-div, I add an onclick-event.
This is the for-loop that I'm talking about:
for (var key in categories) {
categoriesBlock.innerHTML += '<div class="category" id="category' + key + '">' + categories[key] + '</div>';
document.getElementById('category' + key).onclick = function() { showPostsForCategory(key, categories[key]); }
}
where categories is the above array.
The problem is, the onclick is only working for the LAST element in the array. If I check with the Safari-debugger and type "category3.onclick" it says null. If I type "category4.onclick" (which is the last one) it returns the correct function.
How is this possible? And how to solve it?