I hope to find help here, I am stuck.
I use this function to get the exact active li element in a menu (with nth-child):
function getElementPathWithJquery(element) {
return $(element).parents().andSelf().map(function() {
var $this = $(this);
var entry = '';
if(this.nodeName === "BODY" || this.nodeName === "HTML") {
// do nothing
} else {
entry += this.nodeName;
if (this.className) entry += "." + this.className.replace(/ /g, '.');
if (this.id) entry += "#" + this.id;
if ($this.siblings(entry).length > 0) entry += ":nth-child(" + $this.prevAll(entry).length + ")";
}
return entry;
}).get().join(" ");
}
Now, being at the requested level, the parent li-element shall get a addClass(‘active’) attribute, but the following does not work:
if( $('#MENU_MAIN').find("ul.menu-level-3>li").hasClass('active')) {
var path = getElementPathWithJquery($('#MENU_MAIN').find("ul.menu-level-3>li.active"));
$(path).parent().parent().css('border','3px solid red');
}
The reason why I need the exact nth element is the fact that the menu system is a category system an one entry can actually belong to more categories. a solution like:
$('#MENU_MAIN').find("ul.menu-level-3>li.active").parent().parent().css('border','3px solid red');
works, but depending on the number of categories the found entry belongs to, more than just one parent li could have a red border.
Thanks for your help!
Regards,
Robert
You can use
parents()to get all element’s ancestors; you can use a selector to limit the results.