0

Well, I have several projects with title and description in a html code. Every title has a class "nameProject" and I use the following code to get all of them:

var projects = document.querySelectorAll(".nameProject");

And the problem begins here... I'd want that when a user click on one of those titles I can get the value of that specific title. And I'm using this code:

for (var i=0; i<projects.length; i++){
projects[i].addEventListener('click', function(){
alert("Your title is: " + projects[i].value);
});
}

But when I use this code in Javascript, it doesn´t work!! I don't understand what I'm doing wrong :( could you please give me a hand? BTW: Sorry for my english, I'm not native

AlanJR24
  • 15
  • 4

2 Answers2

0

Since var creates a variable in the context of a function (or global context in this case), it's value is that of the latest i (the length of projects).

To solve that problem you can use let, which is scoped to the block (the curly brackets), and the value of each instance of i is preserved in the block.

See this question - What's the difference between using “let” and “var”?

var projects = document.querySelectorAll(".nameProject");

for (let i = 0; i < projects.length; i++) {
  projects[i].addEventListener('click', function() {
    alert("Your title is: " + projects[i].value);
  });
}
<button class="nameProject" value="A">Button 1</button><button class="nameProject" value="B">Button 2</button><button class="nameProject" value="C">Button 3</button><button class="nameProject" value="D">Button 4</button><button class="nameProject" value="E">Button 5</button>

Another option is to use NodeList.forEach(), and skip the need to use indexes:

document.querySelectorAll(".nameProject")
  .forEach(el => {
    el.addEventListener('click', function() {
      alert("Your title is: " + el.value);
    });
  });
<button class="nameProject" value="A">Button 1</button><button class="nameProject" value="B">Button 2</button><button class="nameProject" value="C">Button 3</button><button class="nameProject" value="D">Button 4</button><button class="nameProject" value="E">Button 5</button>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

I would suggest rather than setting up a different event listener, setting up a global one that works across all of them. Also, because you mentioned you are listening for clicks on titles and not fields/buttons, I will be using textContent instead of value in my example below, but please correct me if I am mistaken.

document.addEventListener('click', e => e.target?.matches('.nameProject') && alert(e.target.textContent));
<h2 class="nameProject">Title 1</h2>
<h2 class="nameProject">Title 2</h2>
<h2 class="nameProject">Title 3</h2>
<h2 class="nameProject">Title 4</h2>
<h2 class="nameProject">Title 5</h2>
Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36