Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which class is closer to an element A or B in jquery

Tags:

html

jquery

class

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

like image 344
chriz Avatar asked Dec 08 '22 08:12

chriz


1 Answers

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);
});


Get element check console log

Fiddle Demo


Updated after Comments

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.');
});
like image 199
Tushar Gupta - curioustushar Avatar answered Jan 02 '23 10:01

Tushar Gupta - curioustushar