1

Edit: Please take note that the number of parent divs may vary. It may be one or more.

I am trying everything to get the parent <div> of a <div> with class rat that contains a label. So in this case, the outermost <div> must be returned.

<div> --> Should be returned
    <div>  
        <div class="item box1" id="box1">1</div>
        <div class="item" id="box2">2</div>
        <div class="item" id="box3">3</div>
        <div class="item rat" id="box4">4</div> 
    </div>
    <label>Im the original parent</label>
</div>

It can easily be done when I add class attributes for each div and use closest() but for this case there's no unique selector that I can use.

Or we can take it this way: find the closest label of the <div> with class rat using the above example:

$('.rat') -> selector
DarkMakukudo
  • 2,796
  • 9
  • 35

3 Answers3

1

A recursive approach is the most suitable for your required behavior:

function getParentWithLabel(className) {
    function climbRecusively(node) {
        const parent = node.parent();
        return (parent.find('> label').length ? parent : climbRecusively(parent));
    }
    return climbRecusively($(`.${className}`));
}

$(function() {
    getParentWithLabel('rat').css('background-color', 'grey');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div>  
        <div class="item box1" id="box1">1</div>
        <div class="item" id="box2">2</div>
        <div class="item" id="box3">3</div>
        <div class="item rat" id="box4">4</div> 
    </div>
    <label>Im the original parent</label>
</div>

I hope this helps.

Ghassen Louhaichi
  • 3,961
  • 1
  • 20
  • 32
0

Maybe it would be easier if you apply your style in your global jQuery, like this :

$('.rat').parent().next();
CARA
  • 13
  • 1
  • 2
0

Try this too

   var parentEls = $( ".rat" ).parents();

parentEls.each(function (i, obj) {
    if($(obj).find( "> label" ).length){
    console.log($(obj).attr('class'));
  }
});

Full example : http://jsfiddle.net/harshakj89/ey00czfn/1/

Harsha Jayamanna
  • 1,728
  • 4
  • 21
  • 37