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.
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/
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.
544 Understanding How to Configure Google API Key
680 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
540 Unable to install versioned in Google Colab
544 PHP ssh2_scp_send fails to send files as intended
543 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
© 2024 OneMinuteCode. All rights reserved.