An example:
parent
0 child-a
1 child-b
sub-child
2 child-c
sub-child
sub-child
This works currently in my fiddle, just wondering if there is a cleaner way to go about it. But If a child-(a|b|c) is clicked, the corresponding index is returned (much like jQuery's .index()... but if you click a child's sub-child, you get that same corresponding index.
Code:
$j = jQuery.noConflict();
$j(function() {
// when clicking , show which top level parent element it's in
var element_to_stop_at = $j(".the_top_level_container");
$j(document).click(function(event) {
var target = $j(event.target);
var index_of_top_level_element = 0;
var found_target = false;
var current = target;
while ((current.length > 0) && current.attr("class") != element_to_stop_at.attr("class")) {
current = current.parent();
}
var children = current.children();
current = children.first();
while (current.length > 0 && index_of_top_level_element < children.length) {
if (current.has(target).length > 0 || current[0] == target[0]) {
found_target = true;
break;
}
current = current.next();
index_of_top_level_element += 1;
}
if (false == found_target) {
index_of_top_level_element = -1;
}
console.log("is the " + index_of_top_level_element + " th/nd/rd element in the containing element");
});
});
Is there a simplar / quicker way to do this?
Basically, I would like the functionality of .index(), but if I click a child of one of .the_top_level_container
's children, it should return the same index.
fiddle http://jsfiddle.net/DerNalia/4LSzt/
• click any of the 3 sections boxed/bordered in
• The console will give the index of the the_top_level_container
's children that the clicked element is a part of