Home > OS >  How to use getElementsByClassName for adding a EventListener in javascript
How to use getElementsByClassName for adding a EventListener in javascript

Time:09-11

I am trying to use an event listener for a click on button in JavaScript by using getElementsByClassName method by using following code but it is not working.

document.getElementsByClassName('myBtn')[0].addEventListener("click", myFunction);

function myFunction() {
alert("hello");
}

How can be done using the same method getElementsByClassName.

CodePudding user response:

use this :)

const btn = document.querySelector('.myBtn')


const showAlert = () => {
alert("hello");
}

btn.addEventListener('click', showAlert)
<button >click Me </button>

CodePudding user response:

To apply the same listener for multiple elements based on a same class and using the getElementsByClassName (which you want to use), you should firstly select those element and then loop through them and apply the click event listener for every element.

Here's a demo:

/** select all the elements having the class "click-me" */
const buttons = Array.from(document.getElementsByClassName('click-me'));

/** loop through those elemnts and apply the click listener to each element */
buttons.forEach(btn => btn.addEventListener('click', e => {
  e.preventDefault();
  /** it works! */
  console.log('clicked!') // or: alert('clicked!');
}));
<button >Click Me!</button>
<button >Click Me!</button>
<button >Click Me!</button>
<button >Click Me!</button>

Anyway, this is not the only way that solves your issue, there are many other possible solution like using querySelectorAll method or even implanting Event Delegation for some performance boost.

Learn more about Array.prototype.from method on MDN.

Learn more about getElementsByClassName method on MDN.

Learn more about querySelectorAll method on MDN.

Learn more about Event Delegation on MDN.

CodePudding user response:

I'll add this solution here, just in case someone is looking for getting a unique click on multiple buttons:

HTML:

<button  data-id="1">click Me 1</button>
<button  data-id="2">click Me 2</button>

Javascript:

const btn = document.querySelectorAll('.myBtn');
btn.forEach(btn => btn.addEventListener('click', e => {
    e.preventDefault();
    console.log(e.target.dataset.id)
}));

CodePudding user response:

Works just fine

document.getElementsByClassName('myBtn')[0].addEventListener("click", myFunction);

function myFunction() {
alert("hello");
}
<button >Clickme</button>

  • Related