Darcy Darcy - 6 months ago 83
Javascript Question

jQuery add active class to parent on page load

enter image description here
(All child is active as shown in the picture)
I want to add class="active" to parent when its child is clicked. I manage to add class "active" to parent but all the child is added class= "active" too. What i want is only the chosen child and its parent is "active".

Jquery:

$(document).ready(function(){
var pathname = window.location.pathname;
var filename=pathname.replace(/^.*[\\\/]/, '');

var currentLink=$('a[href="' + filename + '"]'); //Selects the proper a tag
currentLink.parents('.doctormenu').find('li a').removeClass('active');
currentLink.parentsUntil('.doctormenu', 'li').addClass('active');
//currentLink.parent().addClass("active");
//alert(filename);
})


Html:

<ul class="doctormenu">
<li><a href="index.html" class="active">home</a></li>
<li><a href="testabout.php">about</a></li>
<li><a href="testdisease.php">Disease</a></li>
<li><a href="login.html">Search</a></li>




<li><a href="#" >
Services</a>
<ul>
<li><a href="asdqq.html">Self Diagnosis</a></li>
<li><a href="testservice.php">Online Consultation</a></li>
<li><a href="#">Clinic Appointment</a></li>
</ul>
</li>
</ul>

Answer
 $('.doctormenu li a').each(function(){
        // and test its normalized href against the url pathname regexp
        if(urlRegExp.test(this.href.replace(/\/$/,''))){
            $(this).parent().addClass('active');
        }
    });
Comments