checking the current url and then marking a link active based on that url

i want a script that can check the current page uri and then match it to a list of links to be able to add an active class that survives page reloading

So here we go...

1. Get the current page url.

Using this example. get the current url in javascript

2. Get all the nav elements

Need to load all the nav elements into an array and then check if they have the current url



<div class='test-nav'>
<ul class="test-nav-ul" id="test-nav-ul">
<li class="testnavlink"><a href="">Link One</a></li>
<li class="testnavlink"><a href="">Link Two</a></li>
<li class="testnavlink"><a href="">Link Three (alternate link for this page)</a></li>
<li class="testnavlink"><a href="">checking the current url and then marking a link active based on that url</a></li>
<li class="testnavlink"><a href="">Link Four</a></li>


.testnavlink .active {


window.onload = function() { 
    var all_links = document.getElementById("test-nav-ul").getElementsByTagName("a"),
        i=0, len=all_links.length,
        full_path = location.href.split('#')[0]; //Ignore hashes?

    // Loop through each link.
    for(; i<len; i++) {
        if(all_links[i].href.split("#")[0] == full_path) {
            all_links[i].className += " active";

Other Items in javascript
Page Views

This page has been viewed 51 times.

Search Code
Search Code by entering your search text above.

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.


Random Quote
For a long time it had seemed to me that life was about to begin - real life. But there was always some obstacle in the way, something to be gotten through first, some unfinished business, time still to be served, or a debt to be paid. Then life would begin. At last it dawned on me that these obstacles were my life.
Alfred D. Souza