views:

49

answers:

2

It seems to work ok but I don't know if this can be impoved on or not.

I want to select any HTML tag that has a class of edit-text-NUM or edit-html-NUM and change the color of it. Here is what I am using...

jQuery(document).ready(function(){
    jQuery('*')
    .filter(function() {
        return this.className.match(/edit-(text|html)-\d/);
    })
    .css({
        'color': '#ff0000'
    });
});

Does that look ok and is the regex ok?

*edit: Also is this efficient? I am aware that using jQuery('*') might be a bit of a hog if it's a large page. It only has to work from <body> down so maybe it could be changed?

A: 

You can use:

$("[class^='edit-text-'], [class^='edit-html-']")

Note that this isn't exactly the same. For one, it will not work if you have multiple classes.

If you are cautious about performance, a much better solution is to add another class to all elements:

<em class="edit-text-44 edit-text">

Then, you can simply use:

$(".edit-text, .edit-html")
Kobi
Looking again, this only works if this is the only class, class can have multiple values, so my answer isn't exactly the same. `*=` may be more fitting, but has other problems.
Kobi
Yes I just noticed that it doesn't work for multiple class, shall I stick with the filter way then?
fire
Well, no. If you're worried about performance, it is best to add a single class to these elements, and lose the number (or use both: `class="edit-html edit-html-4"`
Kobi
Sorry Kobi it must support multiple class
fire
Good. The best option is to **add another class**.
Kobi
How do you mean?
fire
Its better to add different/custom attribute to these elements, and check for it. this will give better performance than the adding one more class.
Elangovan
@Elangovan: That's a pretty big assumption :) Browsers have optimized finding by class *quite* a bit since it's such a common action now, don't assume what will perform better, the next *******monkey engine always changes the game.
Nick Craver
A: 
jQuery(document).ready(function(){ 
jQuery('body *') 
.filter(function() { 
    return this.className.match(/edit-(text|html)-\d/); 
}) 
.css({ 
    'color': '#ff0000' 
}); 

});

should limit it to the document body

Jan-Frederik Carl
I suppose this answers the 2nd question
fire