views:

46

answers:

4

I am looking for a generalised selector function that does the following:

$(".data").click(function(){
   //insert proper selector
)};

<div class="one">
<div class="data">text</div>
<div class="data">text</div>
<div class="data">text</div>
</div>

<div class="two">
<div class="data">text</div>
<div class="data">text</div>
<div class="data">text</div>
</div>

I want the selector to do the following:

1). Select all divs within the parent div (which means including the one you just clicked).

2). Do NOT select the divs within the other "parent" div.

I also realised that it would be cool if you could filter $(this) (the div you clicked) from the selected items. Consider that a bonus question :)

I've been looking at this from different angles but only found ugly hard coded (to a specific parent). I appreciate any input!

+1  A: 

Maybe you are looking for the .siblings() selector?

$('.data').click(function() {
   $(this).siblings('.data').andSelf()
)};

Assuming you want to select all .data elements that are siblings to the current, selected element. .andSelf() adds the current element to the selection.

Tatu Ulmanen
Thanks, you are right :)
Mattis
+4  A: 

.siblings() selects the siblings of the one that was clicked.

.andSelf() adds the one that was clicked to the set.

Test the example: http://jsfiddle.net/sc23L/

$(".data").click(function(){
     // reference the one that was clicked
   var $clicked = $(this);

     // reference the entire set
   var $divs = $clicked.siblings().andSelf();
});
patrick dw
Perfect, I didn't even realise siblings() existed. That function did exactly what I wanted. Thanks Pat!
Mattis
@Mattis - You're welcome. :o)
patrick dw
.andSelf() that's nifty, I always did .add(this)
Evan Carroll
@Evan - Yeah, it is basically just a wrapper for `.add()` passing in the previous set. http://github.com/jquery/jquery/blob/master/src/traversing.js#L126
patrick dw
Yea, I'm not sure if I like this for this use case, I think I'd rather stick to my old way of doing it `$(this).siblings().add(this)`
Evan Carroll
A: 

Ok, for your other requests

$(".data").click(function(){
   $(this); //code for the clicked element
   $(this).parent(); //code for parent of clicked element
   $(this).siblings(); //code for siblings
)};
digitalFresh
+1  A: 

The siblings selector will not fetch the div that was clicked...

$('.data').click(function(){
   var $clickedDiv = $(this);
   var $allDivs    = $(this).parent().children('div');
});

I don't get the "filter $(this)" part however, having $clickedDiv you can do whatever you wish to it...

acmatos
Thanks, that's also a better answer than any that I found by myself :)
Mattis