0

How can I add an event to an HTML Class after I define it using document.getElementByClassName?

So I have this let pledgeHeader = document.getElementsByClassName("pledge-header");

And when I try to add an event to it pledgeHeader.onclick = function(){this.style.display = "none"} it doesn't do anything. How can I make events work with classes?

Daryl
  • 25
  • 6

2 Answers2

0

document.getElementsByClassName returns an array of elements, not just one element. You can do a forEach on the result and add the handler that way:

let pledgeHeader = document.getElementsByClassName("pledge-header");

pledgeHeader.forEach(el => {
    el.onclick = function(){this.style.display = "none"}
}

Or, if you know you only have one element with that class, you can just do pledgeHeader[0].onclick = .... Basically what you already have, but with [0] to access the first element in the array.

Update

If you know you'll only ever have one "pledgeHeader" why not give that element and id="pledgeHeader", then change your code to let pledgeHeader = document.getElementById("pledgeHeader").

Matt U
  • 4,970
  • 9
  • 28
0

You can loop through the elements and an an event listener to each one. You should use document.querySelectorAll, though, unless you need a live HTMLCollection.

for(const el of document.querySelectorAll(".pledge-header")){
   el.addEventListener('click', function(e){
      this.style.display = 'none';
   });
}

If there is only one element or you only want the first element, you can directly use document.querySelector.

document.querySelector('.pledge-header').addEventListener('click', function(e){
    this.style.display = 'none';
});
Unmitigated
  • 76,500
  • 11
  • 62
  • 80