Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select only one sibling with jQuery?

I have this code:

<ul>   <li class="foo">foo text</li>   <li class="foo2">foo2 text</li>   <!-- more li here -->   <li class="bar">bar text</li>   <li class="bar2">bar2 text</li>   <!-- more li here -->   <li class="baz">clickme!</li> </ul> 

and

$(".baz").click(function() {     alert("test: " + $(this).siblings(".bar")[0].text()); // Doesn't work }); 

siblings(".bar")[0] doesn't work. (no alert box pops up, and no javascript error)

What is the proper way to select one sibling only ?

jsFiddle try

Edit: I don't want to use prev() or next().

like image 392
Benjamin Crouzier Avatar asked Sep 05 '11 13:09

Benjamin Crouzier


People also ask

How can I get next sibling in jQuery?

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.

What does siblings do in jQuery?

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.

Is used to select all the siblings of an element?

To select all sibling elements of an element, we will use siblings() method. The siblings() method is used to find all sibling elements of the selected element. The siblings are those having the same parent element in DOM Tree.

Which of the following jQuery method returns all siblings of the selected element?

jQuery siblings() Method The siblings() method returns all sibling elements of the selected element.


2 Answers

You can use the eq method to reduce the matched set of elements to one at a specific index:

$(this).siblings(".bar").eq(0).text() 

That will select the first element in the set. In your case, you could simply use prev, as the element you're looking for comes directly before the clicked element:

$(this).prev(".bar").text() 

The problem with the array notation method you were using is that it returns the actual DOM node contained within the jQuery object, and that's not going to have a text method. eq is the equivalent jQuery method to do this.

like image 124
James Allardice Avatar answered Oct 04 '22 18:10

James Allardice


You can also grab the first element out of a jQuery object using first:

alert(siblings(".bar").first().text()); 
like image 44
Skylar Anderson Avatar answered Oct 04 '22 17:10

Skylar Anderson