jQuery / wordpress issue with .addClass based on url

I’m have some issues adding a class to 2 navigation links on a theme.

I need to add a class based on a url string as i’m redirecting the page to another.

Read More

I’m using the following code:

<script type="text/javascript">
if (window.location.pathname.indexOf('/category/blog/')){
   if ( $('#nav ul li a span').text().contains('BLOG') ){
       //add class 'current_page_item' to:
       $('#nav ul li').addClass('current_page_item');
   }
}
if (window.location.pathname.indexOf('/category/keepers/')){
   if ( $('#nav ul li a span').text().contains('KEEPERS') ){
       //add class 'current_page_item' to:
       $('#nav ul li').addClass('current_page_item');
   }
}
</script>

Can anyone see why that doesnt work?

I get the following error:

$ is not a function
[Break on this error] if ( $('#nav ul li a span').text().contains('BLOG') ){ 

Related posts

Leave a Reply

2 comments

  1. $(“#nav ul li a span”).text() returns a string, not a jQuery object.
    You cannot call contains on a string, that is the problem.
    Info on the text() function here.

    I think you need to restructure the way you are doing your logic,
    $(“#nav ul li a span”).text() returns the following string:
    HomeBlogBioAboutKeepers
    So your contains logic will evaluate to true on every page of your site.

    I think a better way to do it would be to loop through the li elements, get the text within an individual li span and then set that individual li’s css when it is true.

    HTH

    EDIT:
    This works (I tried it on your site in firebug):

    jQuery('#nav ul li').each(function(){
        //The comparison is case sensitive, Dont use uppercase like in your original
        if(jQuery(this).find('span').text() == "Blog"){ 
            jQuery(this).addClass('current_page_item');
        }
    });