How do I find the ID of the closest top element with a specific class name?

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 DIVs interactive:

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

      

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

+1


a source to share


2 answers


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 the div is clicked using the calss wizard, it doesn't fire an event:

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

      

+2


a source


I thought prev at first , but after some testing I noticed that it won't work on slave

not being placed immediately after another slave

. Grabbing the first match from prevAll worked great.

Demo: http://jsbin.com/ulipi



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

      

0


a source







All Articles