0

Need some help with this code I got off the net

$(document).ready(function(){
jQuery(".linkbar li").each(function(){
var href = jQuery(this).find('a').attr('href');
if (href === window.location.pathname) {
$(this).addClass('current');
}
});
});

if I do document.write(href);

I get "undefined"

If I place var href = jQuery(this).find('a').attr('href'); before .each() function it changes all my links to the current class

below is my HTML and CSS I need to change the css link for the current page, I'm not too good with Jquery/JS. Please explain to me what the problem is and how to solve it.

<div class ="linkbar">

<a href = "/HTS/about-us.php"><li> ABOUT US </li> </a>
<a href = "service.php"><li> SERVICES </li> </a>
<a href = "download.php"><li> DOWNLOAD </li> </a>
</div>

CSS

.linkbar li{
text-decoration:none;
float:left;
list-style-type: none;
font-size:11px;
width:auto;
padding:9px 18px 9px 18px;
}

.current{
background-color:#fecd0f;
vertical-align:center;
color:#fff;
}
A. Mo
  • 142
  • 3
  • 13
  • First of all, don't use `document.write()`, it uses `document.open()` which wipes out all the previous code. Use `alert()` or `console.log()` instead. Secondly, comparing `location.pathname` to value in `href` attribute fails in many browsers, due to some browsers automatically complete the `href` to be a full address with protocol-part too. – Teemu Dec 23 '12 at 12:42

3 Answers3

1

Your HTML is invalid. <li> tags must be inside <ul> tag. Put <a> tags into <li> tags to make find("a") work:

<ul class ="linkbar">
  <li><a href = "/HTS/about-us.php">ABOUT US </a></li> 
  <li><a href = "service.php">SERVICES </a></li> 
  <li><a href = "download.php">DOWNLOAD </a></li> 
</ul>
Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
0

well, buddy you have .find() which finds inside the element and you anchor tag as parent of li tag so instead of that use this:

var href = $(this).parent('a').attr('href');

if it was this you have this:

<li><a href = "/HTS/about-us.php"> ABOUT US  </a></li>
<li><a href = "service.php"> SERVICES </a></li>
<li><a href = "download.php"> DOWNLOAD  </a></li>

still never use find() but use this :

var href = $(this).children('a').attr('href');
Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
0

first you should remove the class and then add the class you can refer to Jquery document for more information : http://api.jquery.com/addClass/

$(this).removeClass(".linkbar li").addClass('current');

and you should absolutely put li tags inside ul

Amir Jalali
  • 3,132
  • 4
  • 33
  • 46