I have this code for creating a menu with submenu using a json via ajax call but I cannot assign the active class to the menu item when I am in a submenu page.
$(document).ready(function () {
$.getJSON('../../menu2.html', function (data) {
$.each(data, function (i, item) {
let menu = $('#side-menu');
$('#side-menu').metisMenu('dispose'); //For stop and destroy metisMenu
var current_page = document.location.href.match(/[^\/]+$/)[0];
var class_item = "";
if (item.nomemenu == current_page) {
var class_item = "active";
}
var arrow = "";
if (item.submenu == "true") {
var arrow = '<span class="fa arrow"></span>';
}
var html = '<li id="menu-' + item.nomemenu + '" class="' + class_item + '">';
html += '<a href="#" id="' + item.title + '">' +
'<i class="' + item.icon + '"></i>' +
'<span class="nav-label">' + item.title + '</span>' + arrow + '</a>';
// SubMenu
if (item.submenu == "true") {
html += '<ul class="nav nav-second-level collapse" name="subelenco">';
//SubMenu Loop
$.each(item.subitems, function (i, subitem) {
if(subitem.link==current_page){
var active_link = 'active';
}else{ var active_link = ''; }
html += '<li class="'+active_link+'" nomemenu="'+ subitem.nomemenu +'"><a href="#" id="' + subitem.link + '" nomemenu="'+ subitem.nomemenu +'">' + subitem.title + '</a></li>';
});
html += '</ul>';
}
html += '</li>';
menu.append(html);
$('#side-menu').metisMenu(); //For stop and destroy metisMenu
});
});
});
I want to assign the active class to the element that has as id "menu-subitem.nomemenu" when subitem.link = current_page .
I tried to insert the code $('# menu -' + subitem.nomemenu).addClass('active') inside the submenu loop, but i don't know whyinside that loop the jquery selector doesn't work in any way.
Do you know any alternative ways with which I can succeed in obtaining this result?