How to add a class when a link has a certain label

Issue

I have a series of links with no a classes. I am unable to manually add any classes in the HTML…otherwise I would. I want to use either JavaScript or jQuery to detect a certain link label and add a class to it if the match is found.

Here is the HTML:

<ul class="menu-main-nav">
   <li><a href="/destination/">Duck</a></li>
   <li><a href="/destination/">Duck</a></li>
   <li><a href="/destination/">Goose</a></li>
</ul>

I want to add a class whenever "Goose" appears. Here is what I attempted… and failed.

$(document).ready(function(){
    if ($("#menu-main-nav li a").text() == "Goose") { this.addClass("itsagoose")};
});

Solution

Use the .filter method:

$("#menu-main-nav li a").filter(function(){
    return $(this).text() == "Goose"; //<--- Only include these elements
}).addClass("itsagoose");

Use .html() instead of .text() if you want an exact match, and don’t want to allow anything else (eg, don’t match <a><span>Goose</span></a>).

Fiddle: http://jsfiddle.net/RWSCY/

Answered By – Rob W

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published