Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Find previous element with class

I have a really simple problem.

How can I find the first previous element of another element? I tried the code below without success.

HTML:

<div class = "A">HERE</div>

<div class="B">
    <div class="C" style="width:50px;height:50px;background-color:#000000;"></div>
</div>

JS:

$('.C').click(function() {

        alert($(this).closest('.A').html());

});

Fiddle: http://jsfiddle.net/Mcujp/4/

like image 398
Peter Lur Avatar asked May 08 '13 22:05

Peter Lur


People also ask

How to Find previous element in jQuery?

jQuery prev() Method The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.

What is prevAll?

The prevAll() method returns all previous sibling elements of the selected element. Sibling elements are elements that share the same parent.

What is used to get the direct parent of an element?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.


2 Answers

If you are trying to get the preceding sibling, use .prev().

If you are trying to get the sibling of the parent (like in your example) use .parent().prev().

like image 78
George Cummins Avatar answered Oct 10 '22 09:10

George Cummins


Try this:

$('.C').click(function() {

        alert($(this).parent().prev('.A').html());

});
like image 23
cortex Avatar answered Oct 10 '22 11:10

cortex