2

I want to select #one, #two and the siblings of #two. Is there a more elegant solution that what I have?

     $('#one, #two').click(function(e){
         e.stopPropagation();
     });

     $('#two').siblings().click(function(e){
         e.stopPropagation();
     });

4 Answers 4

2

The multiple selector exists;

$("#one, #parentIdOfTwo > *").click(function(e) { 
    e.stopPropagation();
});

Lot faster, too.

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

3 Comments

Just note that this is not equivalent to the OPs code. It will also add the event handler to all descendants of #parentIdOfTwo. Better would be #parentIdOfTwo > *.
You are absolutely correct, Mister Kling. I've updated my answer accordingly.
Maybe it's just me, but it took me a while to understand why we need to go one level up.
1

Try this. Take a look I am using andSelf which add the previous set of elements on the stack to the current set, really helpful in your case here.

$('#one').add($('#two').siblings().andSelf()).click(function(e){
      e.stopPropagation();
});

4 Comments

like my solution :) I also thought about andSelf function but with no success
Heads up — there’s a small typo in your code sample: it should be andSelf, not addSelf.
@MathiasBynens - Thanks for letting me know before people dv it :P
@ShankarSangoli No worries :) It was obviously a typo, since your textual description used the correct name.
0
 $('#one, #two').add($('#two').siblings()).click(function(e){
         e.stopPropagation();
     });

Comments

0

You could use:

$('#one, #two').add($('#two').siblings()).click(function(event) {
  event.stopPropagation();
});

…or:

$('#one').add($('#two').parent().children()).click(function(event) {
  event.stopPropagation();
});

Comments

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.