I'm a beginner in Javascript, and I'm struggling to understand some of its functionalities. I can't figure out how the For loop is behaving in my code :
I have two HTML paragraphs, I want to attach to both of them a click
listener to change their color to red using a For loop.
var paragraphs = document.querySelectorAll('p')
for (var i = 0; i < paragraphs.length; i++) {
p = paragraphs[i]
p.addEventListener('click', function(e) {
p.classList.toggle('red')
})
}
Here, only the last paragraph gets colored to red when I click on any one of them.
Someone gave me a solution that I didn't understand at all :
var paragraphs = document.querySelectorAll('p')
for (var i = 0; i < paragraphs.length; i++) {
(function(p) {
p.addEventListener('click', function(e) {
p.classList.toggle('red')
})
})(paragraphs[i])
}
This is working, but I have no clue what is going on in this code.
Can someone help me by telling me why my first code isn't working (even if it seems correct), and explaining just a little bit what's going on in the second code.