Reputation: 143
I'm currently working on a little script and I ran into a little problem.
I want to target an <a>
from a list which has the same href-link than the current Page-URL and give it a Class. I got the href
-part already but I couldn't figure out how to Tag
that specific <a>
with a Class. Here's the code:
var url = window.location.pathname; // for example /somebody
var href = $('a').attr('href');
if (url == href) {
$('the Anchor with the right URL').addClass('myClass');
};
.myClass {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/somebody">Somebody</a>
<a href="/once">Once</a>
<a href="/told">Told</a>
<a href="/me">Me</a>
Upvotes: 0
Views: 34
Reputation: 8589
You can directly select the correct link by using a more specialized selector. The clue is that you can select attributes as well inside it:
var url = '/somebody'; //window.location.pathname; // for example /somebody
var link = $( `a[href="${ url }"]` );
if (link) link.addClass('myClass');
.myClass {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/somebody">Somebody</a>
<a href="/once">Once</a>
<a href="/told">Told</a>
<a href="/me">Me</a>
Upvotes: 2
Reputation: 30739
You need to loop over all the <a>
element using jQuery and check the href
attribute:
var url = '/somebody'
$('a').each(function(){
if($(this).attr('href') === url){
$(this).addClass('myClass');
}
});
.myClass {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/somebody">Somebody</a>
<a href="/once">Once</a>
<a href="/told">Told</a>
<a href="/me">Me</a>
Or you can even use a single liner using the attribute selector:
var url = '/somebody'
$('a[href="' + url + '"]').addClass('myClass');
.myClass {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/somebody">Somebody</a>
<a href="/once">Once</a>
<a href="/told">Told</a>
<a href="/me">Me</a>
Upvotes: 0