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.

 document.getElementsByClassName('hoge-btn').onclick=function(){
  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.

javascript

2022-09-30 11:18

2 Answers

getElementsByClassName returns HTMLCollection instead of a single element.
https://developer.mozilla.org/ja/docs/Web/API/Document/getElementsByClassName


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

varyments= document.getElementsByClassName('hoge-btn');
Array.prototype.forEach.call(elements, function(item){
  // processing using an item
  item.onclick=function(){
    window.alert('View Alerts');
  };
}

You must configure events for all elements, such as .


https://hacknote.jp/archives/21892/


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 event.click The event starts the event listener for all the ancestor nodes unless stopPropagation().

 document.addEventListener('click', function(event){
  if(event.target.classList.contains('hoge-btn')}{
    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.