I'm trying to write an if/else statement in JQuery which can change an element's class by matching 'IN' or 'OUT' (in this case).
For example, I have several <DIV>
with class='IN-something'
OR class='OUT-something'
.
The below would work if I knew the exact CSS class, but all I'll know is that it contains 'IN' or 'OUT'.
So something like this:
if ($(jRow).hasClass('IN-*'))
{jRow.attr( "class", "OUT-foo" );}
else
{jRow.attr( "class", "IN-foo");}
Ideas? Thanks!
How to use wildcards like ('#name*'), ('#name*'), ('#name%') in jQuery selectors? For getting the id that begins or ends with a particular string in jQuery selectors, you shouldn’t use the wildcards $ ('#name*'), $ ('#name%'). Instead use the characters ^and $.
Wildcard Selectors (*, ^ and $) in CSS for classes Wildcard selector is used to select multiple elements simultaneously. It selects similar type of class name or attribute and use CSS property. * wildcard also known as containing wildcard.
This article is intentionally titled and optimised to help people who are googling for the wrong phrase. This is why "jQuery if statement" appaers often. There is no such thing as a jQuery if / else statement. Shocking, isn't it? You might be thinking something like: " There must be! In fact, I'm 99% sure there is! ". It doesn't exist.
The [id^='...'] selector basically means "find an element whose ID starts with this string, similar to id$= (ID ends with this string), etc. You can find a comprehensive list on the jQuery Docs page here. Why don't you just assign class = "instance" to all of them and select them using $ ('.instance')?
if ($(jRow).attr('class').indexOf('IN-') !== 1)
{jRow.attr( "class", "OUT-foo" );}
else
{jRow.attr( "class", "IN-foo");}
You can use the attribute-contains-prefix-selector
(docs) if that will be the entire class value (or at least that is the first class).
if ($(jRow).is('[class |= IN]')) {
This also uses the is()
(docs) method to see if jRow
is a match.
Click here to test a working example. (jsFiddle)
EDIT:
If your point was that you won't know what foo
is, and you need to retain it, I'd do something like this instead:
jRow.attr('class', function(i,cls) {
return cls.indexOf('IN') > -1 ? cls.replace('IN','OUT') : cls.replace('OUT','IN');
});
You can pass a function as the second argument to the attr()
(docs) method. That function has 2 parameters. The first is the current index in the iteration. The second is the current value of the attribute.
The return value is the value that will be set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With