I’m horrible at jQuery, just starting to learn. I have a menu structure that’s in a .NET master page, in each content page that uses the master page I want to apply a different CSS class to an item in a that UL masterpage list.
<section id="navigation">
<nav id="nav-wrap">
<ul id="topnav" class="sf-menu">
<li><a href="Default.aspx">Home</a></li>
<li><a href="About.aspx">About</a></li>
<li class="current"><a href="Purchase.aspx">Buy Now</a></li>
<li><a href="ContactUs.aspx">Contact Us</a></li>
</ul><!-- topnav -->
</nav><!-- nav -->
<div class="clear">
</div>
My block I’m calling with jQuery:
<section id="navigation">
<nav id="nav-wrap">
<ul id="topnav" class="sf-menu">
<li><a href="Default.aspx" id="homelink" title="Home">Home</a></li>
<li><a href="About.aspx" id="aboutlink" title="About">About</a></li>
<li><a href="Purchase.aspx" id="buynowlink" title="Buy Now"><span>Buy Now</span></a></li>
<li><a href="ContactUs.aspx" id="contactuslink" title="Contact Us">Contact Us</a></li>
</ul><!-- topnav -->
</nav><!-- nav -->
<div class="clear">
</div>
When I write the HTML this way, nav element “Buy Now” appears yellow. But this is a master page, so I want to do this with jQuery, so it’s not hardcoded in the masterpage.
<script type="text/javascript">
$(document).ready(function () {
$('#buynowlink').addClass('current');
$('#pagetitle').html('Purchase');
});
</script>
That jQuery code doesn’t appear to apply the CSS or maybe there’s something else going wrong? The line below that sets the H1 title for the page works, so I don’t think it’s an issue of being a page beneath the master page.
What’s weird if I do this: it works, so I must have some sort of CSS issue I don’t get.
<script type="text/javascript">
$(document).ready(function () {
$('#buynowlink').addClass('current');
$('#pagetitle').html('Purchase');
$('#buynowlink').css("color", "yellow");
});
</script>
The ID is on the
a, but you want to add the class on theli, its parent.Therefore, you want
$('#buynowlink').parent().addClass('current');In cases like this, developer tool such as are built into all mainstream browsers now can show you the current state of the DOM, so that you would inspect the Buy Now link and see that the class had been attached to the anchor rather than the list item.