Search code examples
jquery-selectorsjquery-events

jQuery.on() for children with no particular selector


I have HTML structure like this:

<div class="parent">

    <div class="child">
        <div class="something">...</div>
    </div>

    <div class="child">
        <div class="something-else">...</div>
    </div>

    <div class="child">
        ...
    </div>
    ...
</div>

I catch events (like click) on .child elements like this:

$('.parent').on('click', '.child', function() { ... });

However, I would like to get rid of explicit class specification and base on the fact of direct ancestry itself. I want to write the code which would not require any particular classes for children elements. Closest thing to this is:

$('.parent').on('click', '*', function() { ... });

But obviously such handler will spread on deeper descendants (.something, .something-else etc.), not only on the first level.

Is there a way to acheive what I look for, being it using something instead of * or some other way?

P.S. I don't want to use direct binding - $('.parent').children().click(function() {...}); - as it is slower and will not work in case of children being dynamically added.


Solution

  • The selector sought for is > *:

    $('.parent').on('click', '> *', function() { ... });
    

    (The actual solution was suggested by Josh Crozier in the comments, I just reposted it as an answer.)