Compare current url with href

2

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

<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 the 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 did a test by throwing the exact value in the url variable and it works. I would like to know if I should use window.location.href itself or it gives some problem at the time of the comparison.

This href value is just an example, I'm trying to compare the full values, so using 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>

Whenever I'm on the page http://localhost/teste/index.html I need to add a class to the a correct.

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

    
asked by anonymous 05.02.2016 / 18:30

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 entire url.

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

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

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

I hope I have helped!

    
05.02.2016 / 18:36