addEventListener is not working on node

1.3k views Asked by At

I have this simple javascript code.

 var nodeList = document.getElementById(active_tab_selector.attr('id')).getElementsByTagName('span');
for (var i = 0, node; node = nodeList[i]; i++) {
node.addEventListener('click', function() {getChild(this.getAttribute(attribute));
                        }, false);
}

But the click it's not working for some reason, but if I remove getElementById(active_tab_selector.attr('id')) it works fine. Any ideas?

1

There are 1 answers

0
Caxvalencia On

The for loop iterate x times for each node but only the last node is valid for callback then change it by a method that call the addEventListener for node in specific

for (var i = 0, node; node = nodeList[i]; i++) {
  addEventTo( node );
}

function addEventTo( node ) {
  node.addEventListener( 'click', function () {
    getChild(this.getAttribute(attribute));
  }, false);
}

More info about this here