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.
Bruno, could you explain a little more your answer?
– gato
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
Bruno, click the edit button, and put the explanation in the answer :)
– gato
Done! It worked?
– Bruno
@Bruno, in my case I need the url to be exactly the same as href, so I’m using window.location.url
– haykou
got better Bruno +1
– gato