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.
jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.
The siblings() is an inbuilt method in jQuery which is used to find all siblings elements of the selected element. The siblings are those having same parent element in DOM Tree.
jQuery siblings() Method The siblings() method returns all sibling elements of the selected element.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With