Click here to Skip to main content
15,908,166 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear friends,
I have html:
HTML
<div class="w-nav-item-h" id="mydiv">
<a class="w-nav-anchor level_1" href="/english/about-us/word-from-the-chairman">
<span class="w-nav-title">Word from the Chairman</span>
</a>
</div>


And I want to give class "active" to the div "mydiv" according to the the page url with this java script cod :
XML
<script type="text/javascript">
            $(function () {

                $("#mydiv").removeClass('active');

                var lnk = window.location.href;
                lnk = lnk.toLowerCase();
                $("#mydiv a").each(function (index) {
                    if (lnk.indexOf($(this).html().trim().toLowerCase().replace(" ", "-")) != -1) {
                        $(this).parent().addClass('active');
                    }
                });
            });
      </script>


but it is not working :( .. Please help me to find a good solution ???
Posted
Updated 28-Apr-14 23:27pm
v2

Follow the below link:

active-class-navigation-menu

Hope it solves your problem :)
 
Share this answer
 
v2
Your code is not ok.Here:
C#
$("#mydiv a").each(function (index) {
                    if (lnk.indexOf($(this).html().trim().toLowerCase().replace(" ", "-")) != -1) {
                        $(this).parent().addClass('active');
                    }
                });

$(this).html() will return
<span class="w-nav-title">Word from the Chairman</span>


But you need to check if the url from
window.location.href
exists in any hyperlink href value, right? In that case you can use
$(this).attr('href')
instead of
$(this).html()
for the comparison, because $(this).attr('href') will return the url used in the a tag.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900