views:

189

answers:

2

HTML Code:

<div id="1" class="master"></div>
<div id="2" class="slave"></div>
<div id="3" class="slave"></div>

<div id="4" class="master"></div>
<div id="5" class="slave"></div>
<div id="6" class="slave"></div>

let's say, we use $('div').click() to make these DIV elements clickable:

$('div').click(function() {
    var el = $(this);
    var master_id = ???;
    alert(master_id);
});

Then, clicking on DIV elements with class "slave" we need to alert the ID of the closest upper DIV element with class "master", so, if we click on DIV#5 or DIV#6, alerts = "4" (DIV#4), if DIV#2 or DIV#3 - alerts = "1" (DIV#1). But how to do that? ;)

+2  A: 

Updated:

$('div').click(function() {
    var el = $(this);
    var master_id = el.prevAll('.master').attr('id');
    alert(master_id);
});

Edit:
you can also use filters so that when you click a div with calss 'master' it will not fire the event:

$('div').click(function(e) {
    var el =$(this);
    if (!el.is('.master')){
     var master_id = el.prevAll(".master").attr('id');
    alert(master_id);
    }
Marwan Aouida
closest traverses parents, it won't find a sibling element as the OP is looking to do.
great_llama
Thanks for your reply.Unfortunately, your implemention alerts "undefined" when clicking on "slave" DIV elements, and its ID when clicking of "master" DIV elements.
Ken
2 great_llama, do you know the solution?
Ken
I have updated my answer, try now
Marwan Aouida
thanks, Marwan! You are my hero today )
Ken
thanks, guys!!! thanks!
Ken
A: 

I first thought prev would do, but after some testing I noticed it won't work on a slave not placed directly after another slave. Grabbing the first match from prevAll worked perfectly.

Demo: http://jsbin.com/ulipi

$('.slave').click(function() {
    var el = $(this);
    var master_id = $(el.prevAll('.master').get(0)).attr('id');
    alert(master_id);
});
moff