choche7
choche7

Reputation: 59

jQuery addClass to element based on href content

I want to addClass to element on load,

If anchor element contains text = Austin Metro

<a class="market-display" title="">Austin Metro</a>

add class="m-selected" to

<a href="#!/austin-metro" class="">Austin Metro</a>

Thanks!

Upvotes: 0

Views: 10709

Answers (2)

Sky Fang
Sky Fang

Reputation: 1101

var txt = 'Austin Metro';
$('a:contains(' + txt + ')').each(function (i, n) {
    if ($.trim($(n).text()) == txt) {
        $(n).addClass('m-selected');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="market-display" title="">Austin Metro</a>
<a class="market-display" title="">Austin Metro Another</a>

If you want check full text,you need to do this

Upvotes: 0

AmmarCSE
AmmarCSE

Reputation: 30607

If you mean textContent, use contains()

$('a:contains(Austin Metro)').addClass('m-select');

If you mean href, use the attribute contains selector

$('[href*="austin-metro"]').addClass('m-select');

Upvotes: 2

Related Questions