views:

369

answers:

5

I need to loop through some elements in the page and then, for each one, if it had a class beginning with, for example, "C", do something.

$('#dialog li').each(function(){
    if ($(this).hasClass("^C")){
         //do something
    }
}

It may sound silly, but what selector/method should I use on the if clause? Thanks in advance.

+2  A: 

Try the Attribute Starts With Selector. As a bonus, there is no need for the extra if.

$('#dialog li[class^="C"]').each(function() {
    // do something
});
justkt
+1  A: 

Try something like $('#dialog li[class^="C"]')

Soufiane Hassou
The inner quotes are unnecessary: `$('#dialog li[class^=C]')` works, too.
Tomalak
@Tomalak - The jQuery docs have them, but that's good to know!
justkt
@justkt: Unless you have a space in the string you look for (or anything else that has syntactic value in a jQuery selector, like square brackets), the inner quotes are superfluous.
Tomalak
A: 

For more elaborate filters than "starts with" you can use the filter() function:

$('#dialog li').filter( function() { 
  // return true for every element that matches your condition
  return this.className.match(/^c/) != null;
}).each(function(){
  //do something
}
Tomalak
A: 

I don't think that there is a built-in selector to test for classes starting with a string.

There is a selector to test if an attribute starts with a string, so if you know that your elements only have one class (or always start with the class in question), you could do:

$(this).is("class^='C'")

If, however, you can't guarantee either of the above conditions, you would have to manually split out and test each class defined on the element, as described here.

Michael Petito
+1  A: 

Carefull with $('#dialog li[class^="C"]')! It will only match elements, whose class attribute starts with "C" not ones with a class starting with C. For example it will not match <li class="foo Clown">.

AFAIK what you want is not possible mit jQuery alone. You would need to loop through the classes and check each separatly. Something like:

$('#dialog li').filter(function(){
  var classes = this.className.split/\s/;
  for (var i = 0, len = classes.length; i < len; i++) 
    if (/^C/.test(classes[i])) return true;
  return false;
}).each( ... )

Alternativly you should consider changing your approach, and give all elements an additional class and filter by that. This has the addvantage that it can also be used in CSS:

<li class="Clown Clown-Funny">
<li class="Clown Clown-Sad">
<li class="Clown Clown-Rodeo">
RoToRa
Thanks! Excellent approach!
ktMen
Thanks. Just saw an error, which I'll correct. I should have used filter not each.
RoToRa