Compare current url to href

Asked

Viewed 702 times

2

My scenario is this, I have 3 links and I need to identify which one is the same as the url current.

<a href="meulink">Menu 1</a>
<a href="meulink2">Menu 2</a>
<a href="meulink3">Menu 3</a>

The way I used to compare if the url is the same as href was this:

var url = window.location.href;
$('a').each(function(){
  var href = $(this).attr('href');
  if(url===href){
    console.log('works');
  }
});

But it does not work, I even made a test playing the exact value in the variable url and it works. I wanted to know if I should use the window.location.href same or it gives some problem at the time of comparison.

This value of href is just an example, I’m trying to compare the full values, so the use of window.location.href

    <a href="http://localhost/teste/index.html">Menu 1</a>
    <a href="http://localhost/teste/naoindex.html">Menu 2</a>
    <a href="http://localhost/teste/tambemnaoindex.html">Menu 3</a>

Every time I’m on the page http://localhost/teste/index.html I need to add a class to a correct.

Another alternative I tried was the selector $(".nav a[href*='/sobre']").css('color','red');, only instead of 'about' I tried to put the url variable, but to no avail.

1 answer

1

var url = window.location.pathname;
$('a').each(function(){
  var href = $(this).attr('href');
  if (url === href){
    console.log('works');
  }
});

var url = window.location.href; -- takes the whole url.

So you using === means that the data values need to be exactly equal.

var url = window.location.pathname; -- only takes what comes after the host.

Example: www.seusite.com.br/teste.html, using the window.location.pathname he will return only teste.html

I hope I’ve helped!

  • Bruno, could you explain a little more your answer?

  • var url = window.location.href; -- takes the whole url, so using === means that the data values need to be exactly equal. The var url = window.location.pathname; -- only takes what comes after the host. Example: www.seusite.com.br/test.html, using pathname it will return only test.html

  • Bruno, click the edit button, and put the explanation in the answer :)

  • Done! It worked?

  • @Bruno, in my case I need the url to be exactly the same as href, so I’m using window.location.url

  • got better Bruno +1

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.