Reputation: 1059
First of all; I'm sorry if my quesiton is irrelevant, because i'm newbie on jQuery
I have a menu in my website. Here is HTML;
<ul class="page-sidebar-menu">
<li data-link="index.php"><a href="index.php">Home</a></li>
<li data-link="logout.php"><a href="logout.php">Logout</a></li>
</ul>
I'm taking url path to compare with li data-link
to add active
class to li
But unfortunately it's returning undefined.
Here is my javascript / jQuery;
var pathname = window.location.pathname; // Returns path only
var encPath = encodeURIComponent(pathname); // Encoded URL
var splPath = encPath.split('%2F');
var cleanUrl = splPath.pop(); // Clean Url
var dataUrl = $('ul.page-sidebar-menu > li').attr('data-link');
$(dataUrl).each(function( i ) {
if(dataUrl === cleanUrl) {
dataUrl.addClass('active');
}
});
So what's wrong with my code? How can i fix it? Any help greatly appricated.
PS: Sorry for bad English.
Upvotes: 0
Views: 2274
Reputation: 18987
So what's wrong with my code? How can i fix it? Any help greatly appricated.
Problem: is with this line of code $('ul.page-sidebar-menu > li').attr('data-link');
And later you are trying to loop it. The issue is even though this syntax $('ul.page-sidebar-menu > li')
returns you array of matched elements once you use .attr
on it it will return you only the value of first element in the array. Hence you are ending up with only one iteration.
Solution: As already other answers have stated, Loop your $('ul.page-sidebar-menu > li')
and then play with the $(this).data('link')
$('ul.page-sidebar-menu > li').each(function( i ) {
if($(this).data('link') === cleanUrl) {
$(this).addClass('active');
return false; // break loop as we found the link.
}
});
Upvotes: 1
Reputation: 93203
use $().data('link')
to retrieve the value of data-link
attribute :
$('ul.page-sidebar-menu > li')
.filter((index, item) => $(item).data('link') === cleanUrl)
.addClass('active')
Upvotes: 1
Reputation: 14604
You can use each
on li
to get data-link
of each li and match with cleanUrl
var pathname = window.location.pathname; // Returns path only
var encPath = encodeURIComponent(pathname); // Encoded URL
var splPath = encPath.split('%2F');
var cleanUrl = splPath.pop(); // Clean Url
$('ul.page-sidebar-menu > li').each(function(){
if ($(this).attr("data-link") === cleanUrl) {
dataUrl.addClass('active');
}
});
Upvotes: 1
Reputation: 133403
You need to iterate $('ul.page-sidebar-menu > li')
and test each elements data-url
attribute.
$('ul.page-sidebar-menu > li').each(function( i ) {
if($(this).attr('data-link') === cleanUrl) {
$(this).addClass('active');
}
});
You can also use Element.dataset
property to access all the custom data attributes (data-*)
set on element like this.dataset.link
Code can be improved as
$('ul.page-sidebar-menu > li').filter(function( i ) {
return this.dataset.link === cleanUrl;
}).addClass('active');
Upvotes: 3