views:

78

answers:

5

What's the fastest way possible to get a string like "fade" from the classes in the element below?

<div class="MyElement fx-fade"> ... </div>
+1  A: 

Check out JQuery selector regular expressions. It might be exactly what you need! :)

Paranoid Android
I think you did the same thing I did. I misread the question, answered it, and then deleted my answer. The OP isn't asking how to filter elements given the partial match. I think given the element, the OP is asking how to extract part of the attribute.
rchern
Ah! In that case, I apologize for the confusion.
Paranoid Android
+3  A: 
var classes = $('.MyElement').attr('class').split(' ');
for (var i = 0; i < classes.length; i++) {
  var matches = /^fx\-(.+)/.exec(classes[i];
  if (matches != null) {
    // matches[1]
  }
}
Peter Kruithof
thanks :P I love you :D
Alex
+3  A: 

If you wanted to look for something that ended in 'fade' you would use:

$("*[class$='fade']")

And for elements with a class that started with 'fade' you would use:

$("*[class^='fade']")

And to get elements that contain 'fade' you would use (this would be quicker than going through the class names string)

$("*[class*='fade']")

The "*" gets all elements so you could replace this with the element you wanted.

If you want elements that has a classname that starts with 'fx-' you would do:

var classname = "";
var elArray  = $("*[class*='fx-']");

for (var a= 0; a < elArray .length; a++)
{
   //fade
   classname = elArray[a].split("-")[1]; 
}

The array used in the for loop would have all the elements with the classnames like 'fx-'.

Rather than than the for loop checking the elements for the correct class name.

More information at jquery.com

+1 for the jQuery solution
HurnsMobile
+2  A: 

Try this:

$("div[class*='fade']") 

More info

Krunal
A: 

I'd probably go with something like:

//Split class list into individual classes:
var classes = $(".MyElement").attr("class").split(" ");
var fxType;

//Loop through them:
for (var i = 0, max = classes.elngth; i < max; i++) {
  var class = classes[i].split("-");
  //Check if the current one is prefixed with 'fx':
  if (class[0] == "fx") {
    //It is an FX - do whatever you want with it, the type of FX is stored in class[1], ie:
    fxType = class[1];
  }
}
Jake
Careful, `class` is a reserved word in javascript and will cause an error in some browsers.
Peter Kruithof
Oops, had a feeling it might be. Thanks!
Jake