some text
some...">

JQuery: choosing direct 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 MyClass sections next to one click, in the order in which they are located.

This is what I have:

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

I know that adds ALL sections of MyClass; I'm just wondering if there is a quick way to do this.

Thank.

+5
source share
3 answers

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

To get the text of all previous and next elements .MyClassby clicking .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 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(', '));
});
+3
source

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

});

.MyClass ( ), .MyClass, .MyBorder.

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

+2

If you want to get all the brothers and sisters that are within the borders, follow these steps:

$("#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/

+1
source

All Articles