I’m trying to add class active to each li tag in my website but I think something is wrong in my code and I don’t know what is it, anyone can help. I will be appreciated.
$(function () {
var pgurl = window.location.search;
$("li a").each(function () {
if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
$(this).addClass("active");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="menu" class="bg-blue dker">
<li class="nav-header">القائمة</li>
<li class="nav-divider"></li>
<li class="">
<a href="#">
<i class="fa fa-tasks"></i>
<span class="link-title">الأقسام والأصناف</span>
<span class="fa arrow"></span>
</a>
<ul class="collapse">
<li class="">
<a href="?page=Hot-drinks-section">
المشروبات الساخنة</a>
</li>
<li>
<a href="?page=Soft-drinks-section">
المشروبات الباردة</a>
</li>
<li>
<a href="?page=Food-section">
المأكولات</a>
</li>
</ul>
</li>
<li class="">
<a href="?page=Make-an-order">
<i class="fa fa-plus"></i> <span class="link-title">إضافة طلب جديد</span>
</a>
</li>
</ul>
2
Answers
Try the below snippet.
The change I made is
$(this).parent().addClass("active");
, so that the active class will be added toli
, nota
.You need to add class on a parent element example:
$(this).parent().addClass("active");
Try below code