Click here to Skip to main content
15,890,690 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
what is wrong with this code:
JavaScript
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(function(){
  $('li').each(function() {
       var href = $(this).find('a').attr('href');
    if (href == window.location.pathname) {
      $(this).addClass('current');
    }
  });
});
</script>


CSS
.current {
  background:red !important;
  color:blue !important;
}
Posted
Comments
Suvendu Shekhar Giri 9-Jul-15 5:30am    
Code looks fine. What is the problem exactly?
Make sure that your anchor (a) tags contain only the folder path without the domain name in it's href.

JavaScript
$(function(){
$('li').each(function() {
var href = $(this).find('a').prop('href');
if (href == window.location.href) {
$(this).addClass('current');
}
});
});
 
Share this answer
 
Window.location.pathname gives a "/" before path.make sure "/" is appended in your href value, else compare by removing the slash.I have tried using following code and it worked.Please check,

HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(function(){
  $('li').each(function() {
       var href = $(this).find('a').attr('href');
	   console.log(window.location.pathname);
    if (href == window.location.pathname) {
      $(this).addClass('current');
    }
  });
});
</script>
<style>
.current {
  background:red !important;
  color:blue !important;
}
</style>
</script></head>
<body>
<ol>
<li><a href="/C:/Users/akhil.mittal/Desktop/a.html">akhil</a></li>
<li><a href="/C:/Users/akhil.mittal/Desktop/a.html">akhil1</a></li>
<li><a href="/C:/Users/akhil.mittal/Desktop/a.html">akhil2</a></li>
<li><a href="/C:/Users/akhil.mittal/Desktop/a.html">akhil3</a></li>
</ol></body>
</html>
 
Share this answer
 
Comments
Eng.Yahya92 9-Jul-15 4:44am    
it is not the thing of adding / because this code worked perfectly:
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(function(){
$('a').each(function() {
if ($(this).prop('href') == window.location.href) {
$(this).addClass('current');
}
});
});
</script>
Akhil Mittal 9-Jul-15 5:35am    
In this code You are using "window.location.href", be clear what you are trying to achieve because window.location.href does not give "/" before location but gives file path as "file:///C:/Users/akhil.mittal/Desktop/a.html"
Eng.Yahya92 9-Jul-15 5:44am    
thank you for the notice
I combined the two codes somehow and it is working now :D
Akhil Mittal 9-Jul-15 5:46am    
Great :-)
Eng.Yahya92 9-Jul-15 5:44am    
$(function(){
$('li').each(function() {
var href = $(this).find('a').prop('href');
if (href == window.location.href) {
$(this).addClass('current');
}
});
});

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900