1

I'm currently trying to make a javascript function to check if a link on the page links to the same page, and if so, add a class to it.

What I currently have:

$(document).ready(function() {
  var currentPage = location.pathname;
  if $("a[href*=currentPage]") {
  $("a").addClass( "active" );
  }
});

However, this doesn't seem to work. Any help appreciated.

4
  • possible duplicate of jQuery attribute selector variable Commented Sep 25, 2014 at 16:10
  • See the syntax in that question for how to use a variable in an attribute selector. Commented Sep 25, 2014 at 16:10
  • add () => if ($("a[href*=currentPage]")) {...} Commented Sep 25, 2014 at 16:10
  • 1
    There are a couple of basic errors in this code, and a variable should not be included in a string like that. Maybe you would benefit from following some beginners tutorials as well. Commented Sep 25, 2014 at 16:11

2 Answers 2

3
var currentPage = location.pathname;
$('a').each(function() {
    var currentHref = $(this).attr('href');
    if(currentHref == currentPage) {
        $(this).addClass("active");
    }
})

Should do the trick. Pay attention to the fact that some links might include the domain.

Sign up to request clarification or add additional context in comments.

3 Comments

Most links will be relative links, but not necessarily, You may need to remove the website root(s) before comparing to be safe.
How would you remove the website roots?
Unable to get this solution to function, it doesn't add a class to any link to the current page.
2

You can use pure JavaScript (IE 9 and above)

var currentPage = location.href;
var allA = document.getElementsByTagName('A');
for(var i = 0, len = allA.length; i < len; i++) {
    if(allA[i].href == currentPage) {
         allA[i].className = "active";
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.