I have an HTML structure like the following:
<ul id="mainMenu">
<li class="itm_1">
Text...
</li>
<li class="itm_2">
Text...
<ul>
<li class="itm_3">
Text...
<ul>
<li class="itm_4">
Text...
</li>
<li class="itm_5">
Text...
</li>
</ul>
</li>
<li class="itm_6">
Text...
</li>
</ul>
</li>
</ul>
What I like to do, is to add a class to the active element and then in any other element in the same path to add another class like the example bellow:
<ul id="mainMenu">
<li class="itm_1">
Text...
</li>
<li class="itm_2 ANCESTOR_ACTIVE">
Text...
<ul>
<li class="itm_3 ANCESTOR_ACTIVE">
Text...
<ul>
<li class="itm_4">
Text...
</li>
<li class="itm_5 ACTIVE">
Text...
</li>
</ul>
</li>
<li class="itm_6">
Text...
</li>
</ul>
</li>
</ul>
The element that will be considered as active I can find it and add the class of active, but I cannot find the way to add the ancestor_active class in the elements above the active element in the same path.
For now in my script I have the following code:
<?php
$current_page = $page_id; // Lets say is 5
?>
<script type="text/javascript">
var cp = {
p : <?php echo $current_page; ?>
};
jQuery(document).ready(
function($)
{
$('.itm_' + cp.p).addClass('active');
}
);
</script>
Note : The nested arrays are not always with the same depth. In some cases there are other more nested lists and in some othere cases there are not sub lists
how can I climbe to the top element #mainMenu and add the classes “ancestor_active” to each li element in the same path using jQuery?
Use
parents()to look up the tree for all matchesAPI reference http://api.jquery.com/parents/