开发者

PHP, jQuery, selecting all divs within the parent div

I am looking for a generalised se开发者_如何转开发lector 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!


.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();
});
  • http://api.jquery.com/siblings/
  • http://api.jquery.com/andself/


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.


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...


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
)};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜