2

I'm trying to add the same click event to two nested elements inside a div. The HTML structure is like this:

<li class="car>
    <div class="header">
        <h2>Car of the Day</h2>
    </div>
    <div class="car-wrap">
        Content...
    </div>
    <div class="other-content">
        Contains other links and content
    </div>
</li>

The <h2> in the header and the div.car-wrap content are the clickable elements. I cant put the click event on the li.car as there are other link elements on the div.other-content. Also the structure of the HTML may vary depending on the type of result/car. For example in some the div.header may not be present.

So far I have this:

$('#results').on('click', 'li.car:not(".unpinned").car-wrap', function (e) { ...

Which works when I click on the div.car-wrap. But I don't want to replicate it just for the <h2>. Also I am trying to avoid adding another class to the markup if possible. Any suggestions?

0

1 Answer 1

3

You can separate selectors in a single jQuery object with a comma:

$('#results').on('click', 'li.car:not(".unpinned") .car-wrap, li.car:not(".unpinned") .header h2', function (e) { 
   // your code...
});

Also note the space between the :not() and the .car-wrap selector, as it's a descendant.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, I think the same when I read the li.car:not(.unpinned).car-wrap without whitespace between
Thanks. Did not know you can add them like that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.