I have such html piece of code:
<ul class="myClass">
<li><a href="url1.html">first link</a></li>
<li><a href="url2.html">second link</a></li>
<li><a href="url2.html">third link</a></li>
<li><a href="url3.html">fourth link</a></li>
</ul>
The idea is that when I press the link, it should write to the pressed link next property string: class=”active”. For instance, if we have
<li><a href="url1.html">first link</a></li>`
and I press it, the jQuery function should change it to:
<li><a class="active" href="url1.html">first link</a></li>
But my jQuery function doesn’t really work. I’ll very grateful if you can help me.
Here is source of jQuery function:
$(document).ready(function(){
var currentUrl = document.location.pathname;
$('#myClass').each(function() {
if ( currentUrl == $(this).children('a').attr('href')) {
$(this).children('a').addClass('active');
}
});
});
UPDATE
I put log console.log(currentUrl +"=="+ $(this).children('a').attr('href'));
and it said that the state is undefined. I think the “if” condition is not executed, because, I put and else condition and put and alert there, so any pressing calls alert and if condition is never executed.
What you’re trying to achieve, could be shortly written like this: