简体   繁体   中英

jQuery: Selecting immediate siblings

Suppose I have this HTML:

<div id="Wrapper">

  <div class="MyClass">some text</div>
  <div class="MyClass">some text</div>

  <div class="MyBorder"></div>

  <div class="MyClass">some text</div>
  <div class="MyClass">some text</div>
  <div class="MyClass">some text</div>

  <div class="MyBorder"></div>

  <div class="MyClass">some text</div>
  <div class="MyClass">some text</div>

</div>

I want to get the text of the MyClass divs next to the one clicked on, in the order they're in.

This is what I have:

$('#Wrapper').find('.MyClass').each(function () {
  AddressString = AddressString + "+" + $(this).text();
});

I know adds ALL the MyClass divs; I'm just wondering if there's a quick way to do it.

Thanks.

Using .text() , .prevUntil() and .nextUntil()

To get text of all previous and next .MyClass element from clicked .MyBorder :

$('#Wrapper').on('click', '.MyBorder', function() {
  var AddressString = [];
  $(this).nextUntil('.MyBorder').text(function(index, text) {
       AddressString.push(text);
  });

  $(this).prevUntil('.MyBorder').text(function(index, text) {
       AddressString.push(text);
  });
  console.log(AddressString.join(', '));
});

Combination of prevUntil() , nextUntil() with siblings()

$('#Wrapper').on('click', '.MyClass' function() {
    var AddressString = [];
    $(this).siblings('.MyClass').prevUntil('.MyBorder').add($(this).prevUntil('.MyBorder')).text(function(index, text) {
        AddressString.push(text);
    });
    console.log(AddressString.join(', '));
});

You can use .nextUntil() and .prevUntil()

$('#Wrapper').on('click','.MyClass', function(e){
    var self = $(this),
        previous = self.prevUntil('.MyBorder', '.MyClass'), // find the previous ones
        next = self.nextUntil('.MyBorder', '.MyClass'), // find the next ones
        all = $().add(previous).add(self).add(next); // combine them in order

    var AddressString = '';

    all.each(function(){
        AddressString += '+' + $(this).text();
    });

    alert(AddressString);

});

This will find all the .MyClass elements ( in order ) that lie in the same group of .MyClass elements seperated by the .MyBorder elements.

Demo at http://jsfiddle.net/gaby/kLzPs/1/

If you're wanting to get all siblings that are within the borders, the following works:

$("#Wrapper").on("click", ".MyClass", function(){
    var strings = [];
    $(this)
        .add( $(this).prevUntil(".MyBorder") )
        .add( $(this).nextUntil(".MyBorder") )
        .text(function(i,t){
            strings.push( t );
        });
    alert( strings.join(', ') );
});​

Fiddle: http://jsfiddle.net/Uw5uP/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM