frenchie
frenchie

Reputation: 52047

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.

Upvotes: 5

Views: 2631

Answers (3)

Sampson
Sampson

Reputation: 268462

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/

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

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(', '));
});

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196236

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/

Upvotes: 2

Related Questions