Reputation: 145
I'm trying to attach div to an element when it is clicked however when I use .appendChild(div), the element I'm trying to attach to is undefined. I'm pretty confused because it's clearly in the DOM as I'm able to detect the click on it, I just can't append to it.
var pcells = document.getElementsByClassName('priority-cell');
for (var i=0; i < pcells.length; i++) {
pcells[i].onclick = function () {
var div = document.createElement('div');
div.style.backgroundColor = "red";
div.style.height = "10px";
div.style.width = "10px";
pcells[i].appendChild(div);
};
}
Upvotes: 1
Views: 2416
Reputation: 889
I think the problem is here like:
var a = [1, 2, 3, 4, 5];
for(var i=0; i < a.length; i++) {
setTimeout(function() {
console.log(i); //5
console.log(a[i]) //undefined;
}, 1000)
}
If you want to solve, you need closures:
var a = [1, 2, 3, 4, 5];
for(var i=0; i < a.length; i++) {
(function(index) {
setTimeout(function() {
console.log(index); //1,2,3,4,5
console.log(a[index]) //1,2,3,4,5;
}, 1000)
})(i);
}
This is the essence of the problem!
For your code:
for (var i=0; i < pcells.length; i++) {
(function(index) {
pcells[index].onclick = function () {
var div = document.createElement('div');
div.style.backgroundColor = "red";
div.style.height = "10px";
div.style.width = "10px";
pcells[index].appendChild(div);
};
})(i);
}
by the way,the bast is use 'this' or 'event' like:
element.onclick = function(event) {
console.log(this);
console.log(event);
//use 'this' or 'event' do something
}
Upvotes: 0
Reputation: 4244
Try this :
var pcells = document.getElementsByClassName('priority-cell');
for (var i=0; i < pcells.length; i++) {
pcells[i].onclick = function () {
var div = document.createElement('div');
div.style.backgroundColor = "red";
div.style.height = "10px";
div.style.width = "10px";
this.appendChild(div);
};
}
<div class="priority-cell">CLICK HERE</div>
Upvotes: 0
Reputation: 3694
You have a scoping issue. You need to pass in the event details into your handler and use the target property to identify which cell was clicked.
var pcells = document.getElementsByClassName('priority-cell');
for (var i=0; i < pcells.length; i++) {
pcells[i].onclick = function (e) {
var div = document.createElement('div');
div.style.backgroundColor = "red";
div.style.height = "10px";
div.style.width = "10px";
e.target.appendChild(div);
};
}
(JSFiddle: https://jsfiddle.net/z3nhprzp/)
Upvotes: 1