JQuery / wordpress issue with url based .addClass

I am having trouble adding a class to 2 navigation links on a topic.

I need to add a class based on url string as I redirect the page to another.

I am 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 understand why this is not working?

I am getting the following error:

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

      

+2


a source to share


2 answers


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

I think you need to restructure the way you do your logic, $ ("# nav ul li a span"). text () returns the following string: HomeBlogBioAboutKeepers This way your logic will evaluate to true on every page of your site.

I think the best way to do this is to iterate over the li elements, get the text within a particular limit, and then set that personal css when it's true.



NTN

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');
    }
});

      

+1


a source


you should put these lines in



$(document).ready(function(){
     // here
});

      

0


a source







All Articles