For my website navigation I need to add the class \'active\' to the li element depending on if it matches the current URL.
Nav HTML:
If you want to use "pure" ("vanilla") JavaScript, use the following code(assuming that exists):
window.onload = function() {
var all_links = document.getElementById("nav").getElementsByTagName("a"),
i=0, len=all_links.length,
full_path = location.href.split('#')[0]; //Ignore hashes?
// Loop through each link.
for(; i
Using jQuery:
$(document).ready(function(){
var full_path = location.href.split("#")[0];
$("#nav a").each(function(){
var $this = $(this);
if($this.prop("href").split("#")[0] == full_path) {
$this.addClass("active");
}
});
});