Reputation: 23
I have a menu that I am working on and I am trying to change the CSS class on an ID and a child element.
I have a menu that has sections (example: aboutsection). I have added an ID to the ul for that section. What I would like to do, is look at the href attribute for each child anchor of the id, and if the current URL matches any of the links in the children, add a class to the aboutsection ID of "currentTab" and to the actual link add a class of "currentLink."
I have the following jQuery but it is not working.
$(document).ready(function(){
$( "aboutsection" ).each( function(){
if($(this).attr('href') == document.URL){
$(this ).addClass( "currentLink" );
aboutsection.addclass('currentTab');
}
});
});
Upvotes: 0
Views: 92
Reputation: 5840
Your general approach of using
$(elementId).addClass('newClassName');
is correct.
However, your entire loop might turn out to be useless because your selector may not return anything.
If aboutsection is an element's class, try
$('.aboutsection').each(function(){
$(this).addClass('currentLink');
});
which is practically the same as:
$('.aboutsection').addClass('currentLink');
If aboutsection is an element id (should be unique on your entire page), try
$('#aboutsection').addClass('currentLink');
Upvotes: 2
Reputation: 706
$( "aboutsection" ).each( function(){
is not correct.
if "aboutsection" is a class you need:
$( ".aboutsection" ).each( function(){
or if is an id you need:
$( "#aboutsection" ).each( function(){
Upvotes: 0
Reputation: 53198
Your code is looking for a HTML element wrapped in a tag named aboutsection
. If this is actually the ID of your <ul>
element, you''ll need to update your code.
Also, aboutsection.addClass()
will have no effect, since it's undefined:
$(function() {
$('#aboutsection').each(function() {
if($(this).attr('href') == document.URL)
{
$(this).addClass('currentLink');
$(this).addclass('currentTab');
}
});
});
Upvotes: 0