Use jQuery to map the current url to herf in UL and add a class if they match

I have dynamically created UL. I want to use jQuery to use the current URL, search on the specified UL, and search for any with the appropriate href. If it is found, add the class "current_page".

I came up with this, but it doesn't seem to be the trick.

$(document).ready(function() {  
    $("ul.nav_cat_archiveli").find("a[href='"+window.location.pathname+"']").each(function() {
        $(this).addClass("current_page");
    });
});
+5
source share
2 answers

You can play with window.location , which will return the current page URL, as well as the href window.location property

+1
source
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var windowLocationPathname = "/HTMLPage16.htm";  // For testing purpose.

            //Or

            //var windowLocationPathname = window.location.pathname;

            $('ul.nav_cat_archiveli').find('a[href^="' + windowLocationPathname + '"]').addClass('currentPage');
        });
    </script>
    <style type="text/css">
        .nav_cat_archiveli
        {
            list-style: none;
        }

        a.currentPage
        {
            color: Red;
            background-color: Yellow;
        }
    </style>
</head>
<body>
    <ul class="nav_cat_archiveli">
        <li><a href="/HTMLPage14.htm">Test 1 (/HTMLPage14.htm)</a></li>
        <li><a href="/HTMLPage15.htm">Test 2 (/HTMLPage15.htm)</a></li>
        <li><a href="/HTMLPage16.htm">Test 3 (/HTMLPage16.htm)</a></li>
        <li><a href="/HTMLPage17.htm">Test 4 (/HTMLPage17.htm)</a></li>        
    </ul>
</body>
</html>
0
source

All Articles