I want to make my click listener on specific element extend to all children, this mean that if I click inside any element, it will show a simple console.log message.
Here is my code =>
<div class="x">
<span id="a">hello</span>
<p name="b"> this is p tag!</p>
<div>this is div</div>
<div name="c" id="c">one more div</div>
<a>just a tag test</a>
</div>
document.querySelectorAll('[class="x > *"]').onclick = function(e) {
return console.log('clicked!')
}
Currently, if I click on "X" class or anchor tag, I do not receive the console.log message. How can I solve this?
Thank you.
>Solution :
document.querySelectorAll returns a NodeList; setting .onclick on a NodeList does nothing.
You have two choices:
-
Set a handler on each of the elements:
document.querySelectorAll(selector).forEach(el => el.onclick = handler), or better yet,document.querySelectorAll(selector).forEach(el => el.addEventListener('click', handler)) -
Set a handler on an ancestor element, and let it catch the event as it propagates up the tree.