<div id="test1" onlick="testFunction()" role="button" tabindex="0">A custom button</div>
<div id="test2" role="button" tabindex="0">Another custom button</div>
<button class="test3">A final button</button>
<ul id="test4">
<li>Cookies</li>
<li>Cream</li>
</ul>
<div id="test5">Just a div, not clickable </div>
document.getElementById('test2').addEventListener('keypress', function() {
console.log("foo");
}
)
document.querySelectorAll('.test3').forEach(item => {
item.addEventListener('click', event => {
console.log("bar");
})
})
document.getElementById('test4').onclick = function(event) {
let target = event.target;
if (target.tagName != 'li') {
event.target.addClass('highlight');
}
};
I'm interested in using JavaScript (preferably no jQuery or other library) to find all DOM elements which have events attached to them. There are many ways to find elements that have HTML event attributes like #test1
. But it is unclear how to find elements that have events added via a script like #test2
or .test3
or the <ul id="test4">
. A correct answer would return an array with four elements.
An even better response would additionally find the elements using event delegation like the <li>
but it seems like that may not be possible.
EDIT: querySelectorAll() now selects the test3 class instead of test3 tag