jquery if link = page url

10,247

Solution 1

Here's a short way to select links like that:

$('ul > li a[href$="' + window.location.pathname + '"]').css('font-weight','bold');

Or perhaps better like this, which does an exact match of both pathname attributes:

$('ul > li a[href]').filter(function() {
    return this.href.pathname === window.location.pathname;
}).css('font-weight','bold');

If you're using the full domain in the href, you could change it to:

return this.href === window.location;

Solution 2

Here is a great solution I have used:

$(function(){
       $("a").each(function(){
               if ($(this).attr("href") == window.location.pathname){
                       $(this).addClass("selected");
               }
       });
});

Source - https://css-tricks.com/snippets/jquery/highlight-all-links-to-current-page/

Share:
10,247
Alex
Author by

Alex

Updated on June 09, 2022

Comments

  • Alex
    Alex almost 2 years

    ok pretty simple but i dont know how...

    i just want to make an active state (probably just make it bold)

    my menu is ul-li

    i cant figure out how to write it so if the url matches with one of the links, make the link bold

    please help

    thanks for your time

  • Sam152
    Sam152 about 7 years
    Minor correction, but it should be "this.pathname" instead of "this.href.pathname".
  • Stephan Ahlf
    Stephan Ahlf almost 7 years
    return this.href === window.location.href;
  • Marco Panichi
    Marco Panichi over 5 years
    I don't think it works. href could be https://www.-----.com/folder1/folder2/name-of-page while window.location.pathname is just /folder1/folder2/name-of-page