JQuery if/else statement matching a wildcard CSS name

Neokoenig picture Neokoenig · Jan 17, 2011 · Viewed 7.3k times · Source

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!

Answer

Sarfraz picture Sarfraz · Jan 17, 2011
if ($(jRow).attr('class').indexOf('IN-') !== 1)
  {jRow.attr( "class", "OUT-foo" );}
else  
  {jRow.attr( "class", "IN-foo");}