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 !

0

4 Answers 4

3

Try this simple statement:

$("a[str='10']").addClass("old");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you its the simplest way !
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.

2 Comments

Thank you for this good expression ! You are right str is not a valid value but in my case sad to say necessary :-(
@Phantom001 use the quotes around the value atleast..
1
$('a[str=10]').removeClass('old').addClass('new');

Comments

1

try this

$('a[str=10]').removeClass('oldClass').addClass('newClass');
$('a[str!=10]').removeClass('newClass').addClass('OldClass');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.