0

Edit: Thanks for the help! using "console.log(this.getAttribute('data-x'));" fixed my problem

I'm working on a project where I want to have a grid of Div's each with a unique coordinate. I'm using data- tags to hold two coordinates and I want to console log the values when each div is clicked.

HTML:

<div class="cell" data-x="1" data-y="1"></div>

...and so on until

<div class="cell" data-x="12" data-y"12"></div>

JavaScript

var cell = document.querySelectorAll('.cell')
for (var i = 0; i < cell.length; i++){
cell[i].addEventListener('click',function(){
console.log(cell[i].getAttribute('data-x'));
});
};

This code is just trying to console log the data-x value for now, but its not working... Can anyone suggest a solution?

DanielK
  • 3
  • 1
  • 3
  • try `cell[i].dataset.x` - though you say `but its not working` - so try `console.log(cell.length)` just after `var cell = document.querySelectorAll('.cell')` - if it's ZERO it's because the code is running before the DOM has any such elements – Jaromanda X Jun 24 '17 at 01:14
  • `i` is off inside the click-handler. Either use `console.log(this.getAttribute('data-x'));` or a closure like `document.querySelectorAll('.cell').forEach(function(cell){ cell.addEventListener('click', function(){ console.log(cell.getAttribute('data-x')); }); })` – Thomas Jun 24 '17 at 01:17
  • 1
    ... Instead of using `cell[i]` that causes the above closure problem, just use `this` which is the same as `cell[i]`. – ibrahim mahrir Jun 24 '17 at 01:19
  • @Thomas .forEach() is not supported in all browsers on node lists. – Scott Marcus Jun 24 '17 at 01:31

0 Answers0