I’m using the twitter Bootstrap framework and I want to change the active link depending on the page showing. (If this is not appropriate for Stackoverflow, just delete it)
Basic nav menu html is below. Notice the class ‘active’? This highlights the active link.
<ul class="nav">
<li class="active"><a href="default.aspx">View Programs</a></li>
<li><a href="addprogram.aspx">Add Programs</a></li>
<li><a href="contacts.aspx">Contacts</a></li>
</ul>
jQuery Code … I remove the class ‘active’ from all li tags and add it back to the li tag with the link to the page showing.
$(document).ready(function () {
$("ul.nav > li").removeAttr("class");
$("ul.nav > li a[href*='contacts.aspx']").parent("ul.nav > li").addClass("active");
});
This know gives me …
<ul class="nav">
<li><a href="default.aspx">View Programs</a></li>
<li><a href="addprogram.aspx">Add Programs</a></li>
<li class="active"><a href="contacts.aspx">Contacts</a></li>
</ul>
This works, but is it the correct way to do it?
What you did is fine. But instead of removing the class attribute in the tag, I would do this instead because in the future you may play with multiple classes.