1

i have an problem. I have an div element within x subelements (buttons etc) and the subelements i will add an eventlistener with a loop, i have provided a fiddle:

<button test="page1">page1</button>
<button test="page2">page2</button>
<br>
<button test2="page1">page1</button>
<button test2="page2">page2</button>



var location = document.querySelectorAll("[test]");
var location2 = document.querySelectorAll("[test2]");

location.forEach(function(e1, e2){
  location[e2].addEventListener("click", function(){
    alert(location[e2].getAttribute("test"));
  });
});

for(var i = 0; i < location2.length; i++){
    location2[i].addEventListener("click", function(){
    alert(location2[i].getAttribute("test2"));
  });
}

https://jsfiddle.net/zeus1309/jqL8b0rt/

The version with foreach works. but the one with for not. I dont understand why.

  • Be carefull, NodeList instance (from document.querySelectorAll) has no forEach method. Write this before : "NodeList.prototype.forEach = Array.prototype.forEach;" – karkael Feb 24 '17 at 13:21

1 Answers1

0

Instead of location2[i].getAttribute("test2") use this.getAttribute("test2").

Note: Inside the forEach() function, you don't have to use both arguments.

var location = document.querySelectorAll("[test]");
var location2 = document.querySelectorAll("[test2]");

location.forEach(function(e){
  e.addEventListener("click", function(){
    alert(e.getAttribute("test"));
  });
});


for(var i = 0; i < location2.length; i++){
 location2[i].addEventListener("click", function(){
   alert(this.getAttribute("test2"));
  });
}
<button test="page1">page1</button>
<button test="page2">page2</button>
<br>
<button test2="page1">page1</button>
<button test2="page2">page2</button>
kind user
  • 40,029
  • 7
  • 67
  • 77