Question

I have a sidebar navigation that lists blog entry titles down the side of the page. I am trying to write some jquery that will check the text in the title of the current full blog entry page and match it with the corresponding title in the sidebar navigation so that I can apply a class to style for an active state link ... but I'm not quite getting it! Here is the link to an example page: http://ncw-commercial.com/property-listings/eastpoint-plaza-lot.html, and below is my current code. I have also tried using :contains but could not figure out how to get that to work with a variable rather than direct text.

$('.single-journal-entry-wrapper .journal-entry .title').each(function(){ 
      var activeTitle = $(this).text();
      $(".feedburnerFeedBlock .headline a").filter(function(index) {
         return $(this).text() == "activeTitle";
      }).parent().addClass("activeTitle");
}); 
Was it helpful?

Solution

I think you are very very close (assuming the selectors are correct). Just remove the quotes around activeTitle (otherwise you are comparing against the string "activeTitle"):

$('.single-journal-entry-wrapper .journal-entry .title a').each(function(){ 
      var activeTitle = $(this).text();
      $("#sidebar1 .section .headline a").filter(function(index) {
         return $(this).text() == activeTitle;
      }).parent().addClass("activeTitle");
});

You can also use the :contains() selector:

$('.single-journal-entry-wrapper .journal-entry .title a').each(function(){ 
      var activeTitle = $(this).text();
      $("#sidebar1 .section .headline a:contains('" + activeTitle + "')")
      .parent().addClass("activeTitle");
});

The link to the page is not helping much. Somehow I don't see which title you want to match with which link. Sorry.

Update:

Ok I figured it out. The problem was, that both strings (the title and the one in the link didn't match because the title had a   in it (Eastpoint Plaza Lot) where the link in the sidebar had not. And although this is converted to a blank if you call .text(), it somehow does not match.

Now this could be solved by get the title via .html() and replace the   with a space:

$('.single-journal-entry-wrapper .journal-entry .title a').each(function(){ 
      var activeTitle = $(this).html().replace(' ', ' ');
      $("#sidebar1 .section .headline a:contains('" + activeTitle + "')")
      .parent().addClass("activeTitle");    
});

For testing I copied all your HTML code and it works for me now. Give it a try. I think the biggest Problem is, that titles may have HTML encoded characters in it, so find a library that convert them if you run into more problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top