I am having some trouble with a fairly simple piece of vanilla Javascript. All it does, is get all p elements by their tag name, and attach an event handler to each one, which calls a function that changes the colour to red.
Outside the callback function el
refers to the correct element, 1-6. But inside the loop, it always refers to the last one, despite javascript's lexical variable scoping nature. Why is this, and what can be done to implement indended behaviour?
Fiddle: https://jsfiddle.net/7j4bg68g/
<p>1 This is a test.</p>
<p>2 This is a test.</p>
<p>3 This is a test.</p>
<p>4 This is a test.</p>
<p>5 This is a test.</p>
<p>6 This is a test.</p>
...
function takeAction() {
this.style.color = 'red';
}
var els = document.getElementsByTagName('p');
for (var i = 0; i < els.length; i++) {
var el = els[i];
// logs els 1 to 6 as expected.
console.log(el.innerHTML);
el.addEventListener('click', function() {
// logs "6 This is a test.", and makes the last <p> tag red,
// regardless of which <p> element you click on.
console.log(el.innerHTML);
takeAction.call(el);
}, false);
}