<div class='red'>
<span class='orange'>
<div class='green'>
<div class="yellow">
<p>who is closer to me red or green??</p>
</div>
</div>
</span>
</div>
above is my html, i want to compare green or red which one is closer to <p>
in jquery??, i tried with
$(this).parents().hasClass("red");
but that will not work for me.. help me..
Fiddle Demo
One Way :)
$('p').click(function () {
var cls = $(this).parents('div').filter(function () { //filter all div parents
return $(this).is('.green, .red'); //filter element who have class green or red
}).attr('class'); //get the attr of the first matched element
alert(cls);
});
Fiddle Demo
Updated Fiddle Demo
$('p').click(function () {
var cls = $(this).parents('div').filter(function () { //filter all div parents
return $(this).is('.green, .red'); //filter element who have class green or red
}).attr('class'); //get the attr of the first matched element
alert(cls.match(/(green|red)\s?/i)[0] + ' is closer.');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With