Peter Lur
Peter Lur

Reputation: 758

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/

Upvotes: 23

Views: 81105

Answers (4)

if you want to target closest children of top parent you can do so as something define below.

lets assume you have an HTML like

<div class="top-parent">
  <div class="parent">
    <button class="add-button">Child of 1st Parent DIV</button>
  </div>
  <div class="parent">
    <button class="add-button">Child of 2nd Parent DIV</button>
  </div>
</div>
<script>
$(document).on('click','.add-button',function(){
   $(this).parents('.parent').prev().closest('.parent').find('.add-button').text('im clicked by one of the button next to my parent')
   $(this).parents('.parent').remove();
})
</script>

similarly if you want to target grandparent next parent containers children just change .prev() to .next()

hope i made it simple to define :)

Upvotes: 0

George Cummins
George Cummins

Reputation: 28906

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().

Upvotes: 30

hnafar
hnafar

Reputation: 611

$('.C').click(function() {
   alert($(this).closest('.B').prev('.A').html());
});

Upvotes: 5

cortex
cortex

Reputation: 5206

Try this:

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

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

});

Upvotes: 9

Related Questions