1

I have a three divs each with class "card". I want to perform a function when a user clicks any of the divs with this class. Simply, I can use onclick on each of the divs (and it works also) but it is rather a lengthy wok. So I ended up with this:

document.getElementByClassName("card").addEventListener("click", redirect);

But after some research I came to know that getElementByClassName returns a collection and we have to use index values to access each element with it, I finally ended with this:

var card = document.getElementByClassName("card");
for (var i = 0;i < card.length;i++){
    card[i].addEventListener("click", redirect);
}

But it is definitely not working.

I know that this is one of the most common problems, but I am not satisfied with any of the answers to related questions in the context of my problem.

Praneet Dixit
  • 1,393
  • 9
  • 25
  • 3
    The function is `getElementsByClassName` - *plural*. You then need to `forEach` over them to apply event listeners. However, you should also consider if you'd be better off delegating the event to the parent container. – Niet the Dark Absol Jun 19 '20 at 12:55
  • 1
    `getElementsByClassName()` returns a **list** of elements. – Pointy Jun 19 '20 at 12:55
  • 5
    There is a beautiful feature in the browser called console. Please open it once and see if you have any errors like: `document.getElementByClassName is not a function` – palaѕн Jun 19 '20 at 12:56
  • Could you please provide here `console.log(card)` ? – Dmitry Leiko Jun 19 '20 at 12:57
  • @palaѕн Yes, I am able to see exactly the same error. – Praneet Dixit Jun 19 '20 at 12:59
  • @Pointy on a [similar question](https://stackoverflow.com/questions/42751308/getelementbyclassname-isnt-working#comment110479671_42751308) , there was a comment by a user to do the following to access an element from a class : >document.getElementsByClassName("edit")[0].innerHTML = localStorage.userEdits; – Praneet Dixit Jun 19 '20 at 13:05

1 Answers1

1

Use getElementsByClassName instead of getElementByClassName it's a very subtle difference so we all stumble across it from time to time

const card = document.getElementsByClassName("card");

for (let i = 0; i < card.length; i++) {
  card[i].addEventListener("click", redirect);
}

function redirect(event) {
  console.log(event.target.textContent);
}
<div class="card">Item 1</div>
<div class="card">Item 2</div>
<div class="card">Item 3</div>
Mario
  • 4,784
  • 3
  • 34
  • 50
  • Thanks. It is working in the snippet but I can't figure out why it isn't working on my project – Praneet Dixit Jun 19 '20 at 13:17
  • If you have made the change that I mentioned in the console, it could be a different error, take a look at the browser console and share the message if you find any error – Mario Jun 19 '20 at 14:21
  • Well it is working now. I put the block of code inside the body of the function redirect and it worked. – Praneet Dixit Jun 20 '20 at 03:30