Action to be taken when an element with a specific class is clicked

Asked 2 months ago, Updated 2 months ago, 1 views

This is my first time asking a question.
I would like to use the external link js to create an action that will be applied when an element with a specific class is clicked.

  window.alert('View Alerts');

I tried writing this code, but clicking on the class element "hoge-btn" doesn't work.
Is there something wrong?
I'd appreciate it if you could give me some advice.


2022-09-30 11:18

2 Answers

getElementsByClassName returns HTMLCollection instead of a single element.

because you must specify a target to click on getElementsByClassName("hoge-btn")[0] and other elements.

varyments= document.getElementsByClassName('hoge-btn');, function(item){
  // processing using an item
    window.alert('View Alerts');

You must configure events for all elements, such as .

2022-09-30 11:18

Registering an event listener one by one is a pain in the neck, so you can use document to process the The event starts the event listener for all the ancestor nodes unless stopPropagation().

 document.addEventListener('click', function(event){
    alert('View Alerts');
}, false);

This code can be executed at a time when there is no element in the document that has a hoge-btn class, but it can still handle the click of the element with the hoge-btn that you added later.

2022-09-30 11:18

If you have any answers or tips

© 2022 OneMinuteCode. All rights reserved.