0

Good Morning,

Sorry i think its a simple "stupid" question but i have a big blank.

I want to change a class if the attr value is equal to a given value.

I have the following:

 <a str=10 href="start.php class="old">Start<a>

So if str attr from a is 10 i will set the class to class="new"

I have tried somethig like:

$('a.attr.subnr.10).addClass('old');

I think its to early in the morning :-(

Thank you !

Phantom001
  • 71
  • 1
  • 8

4 Answers4

3

Try this simple statement:

$("a[str='10']").addClass("old");
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
2

First of all, str is not a valid attribute, consider using data-str

You can do it like

if($('a').attr('data-str') == 10) {
    $('a').addClass('add_class');
}

Demo


Make sure you use a specific selector, this is a generalized one, so consider using something like .parent a


If you want a pure CSS solution, than you can also use attr=value selector like

a[data-str="10"] {
   color: red;
}

This won't add a class to your element, but you can target it using the above selector.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
1
$('a[str=10]').removeClass('old').addClass('new');
Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57
1

try this

$('a[str=10]').removeClass('oldClass').addClass('newClass');
$('a[str!=10]').removeClass('newClass').addClass('OldClass');
Ravi
  • 853
  • 8
  • 17