Question

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

Was it helpful?

Solution 2

Try using .parentsUntill() at this context,

var xCollection1 = $('p').parentsUntil('.red');
var xCollection2 = $('p').parentsUntil('.green');

if (xCollection1.length < xCollection2.length) {
    alert('red is nearer');
} else {
    alert('green is nearer');
}

DEMO

OTHER TIPS

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

Here's a relatively simple solution:

var item = $(this).closest(".red, .green");
if (!item.length) {
    console.log("no red or green parents");
} else if (item.hasClass("red")) {
    console.log("red");
} else {
    console.log("green");
}

Working demo: http://jsfiddle.net/jfriend00/Xcz98/


And, in case you're curious, here's a plain javascript method:

// pass starting node and space separated class list
// returns the class from the list it found first or "" if none were found
function findClosestParentClass(node, classes) {
    var regex = new RegExp(" " + classes.replace(" ", " | ") + " ");
    var cls, match;
    node = node.parentNode;
    do {
        cls = " " + node.className + " ";
        match = cls.match(regex);
        if (match) {
            return match[0].replace(/ /g, "");
        }
        node = node.parentNode;
    } while (node && node !== document.documentElement);
    return "";
}

Working demo: http://jsfiddle.net/jfriend00/f3dHm/

You can try this :

var parents = $(this).parents('div').map(function() {                
      return $(this).attr('class');
    }).get();    

if(parents.indexOf("red") < parents.indexOf("green")) {
     alert('red is closer to me');   
} 
else {
       alert('green is closer to me');   
}

Working Example

So, the greater the index in the parents() array, the farther it is in the DOM tree away from your <p> element. Now it is a matter of traversing through the array, and looking at each class name.

To see which is closer in the DOM, you need to compare the index of each element that you want to check for.

In this case, elements with class .red is at index 3, and elements with class .green are at index 1. This means that green is closer.

$(document).ready(function() {
    var indexOfRed;
    var indexOfGreen;
    $('p').click(function() {
        $(this).parents().each(function(index, el) {
            if ( $(el).hasClass('red') ) {
               indexOfRed = index;
            }
            if ( $(el).hasClass('green') ) {
              indexOfGreen = index;
            }
        });
        if(indexOfRed < indexOfGreen) {
             alert('red is closer to me');   
        } else {
             alert('green is closer to me');   
        }
    });
});

http://jsfiddle.net/JvNmT/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top