Getting a little headache with jQuery in my attempt to add a toggle button to each element that contains a specific class.
As i use jQuery's .each( , i was hoping to do it at the loop i add my identifier class.
But somehow it keeps append my html code in a loop to each li instead of the li.has-children
This is my current code:
function addLevelClass($parent, level) {
// fetch all the li's that are direct children of the ul
var $children = $parent.children('li');
// loop trough each li
$children.each(function() {
// get the ul that is a direct child of the li
var $sublist = $(this).children('ul');
// if an ul was found
if ($sublist.length > 0) {
$sublist.addClass('slideable-submenu');
// add a class to the current li indicating there is a sub list
$(this).addClass('has-children level-'+level);
//last attempt before ask on SO
if( $(this).hasClass('has-children level-'+level) ){
$( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');
}
// repeat the process for the sublist, but with the level one higher
// = recursive function call
addLevelClass($sublist, level+1);
}
});
}
// call the function to add level classes on the upper most ul
addLevelClass($('.header-mobile-menu'), 0);
//$( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');//Adds toggle buttons everywhere
So the idea is to get:
$( 'li.has-children span a' ).after( '<span class="sub-menu-toggle"></span>');
In it's correct position.
if( $(this).hasClass('has-children level-'+level) )as it's always going to be truefind('a')but should have beenfind('span:first'). We keep learning.