Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript make click listener extend to all childern

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading