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/