views:

78

answers:

3

I want to add a class to any DOM element that is on the page now or in the future that has a specified class and meets some criteria

so for some pseudo code

$('.location').live('load',function(){
    if($(this).find('input:first').val().substr(0,1) == "!"){ $(this).addClass('hidden')}
});

of course this does nothing

EDIT NOTE

this does not work either

$('.location').live('load',function(){
    alert('adding location');
});
A: 

You can't do this.

You'll have to do:

$('.location').filter(function () {
    return ($(this).find('input:first').val().substr(0, 1) == "!");
}).addClass('hidden');

To apply it to all currently elements on the page, and then manually add the 'hidden' class to future elements you add to the DOM.

Matt
hoping I can find something that will cover them all but this may be the only way
mcgrailm
If you do it correctly, it wouldn't have to be manually.
Gregg
@Gregg: If you know a correct solution to add classes automatically to select elements that are added to the DOM at a later stage, please share it.
Matt
I did, see my answer.
Gregg
@Greg: Wow, didn't realise livequery was that good :).
Matt
A: 

The code .subtr(0,1) = "!" likely doesn't do what you want.

Justice
yes it does checking to see if the first character in the string is "!" I can't event get the alert me
mcgrailm
There is a single `=` character there.
Justice
yes sorry my bad i had a typo you are correct but this is not the answer to the problem thanks for your help
mcgrailm
+4  A: 

jQuery's live() feature is just subset of the livequery plugin, which is much richer. If you use livequery you could do something like..

$('.location').livequery(function() {
   // perform selector on $(this) to apply class   
});

That will cover existing elements plus any future elements added to the DOM.

Gregg
so this is a plugin that needs to be included ?
mcgrailm
Yes. http://docs.jquery.com/Plugins/livequery
Gregg
+1 Didn't see this answer when I answered. Deleted mine. :o) Although I don't think I'd say that one is a subset of the other. The way they work is completely different.
patrick dw
@patrick. Maybe subset is the wrong word. What I mean is livequery() existed before jQuery added it's own live() feature. And by subset I mean that the livequery plugin seems to be more robust (less about specific events) since you don't have to apply livequery to click,hover,change, etc.
Gregg
@Gregg - Yes, in terms of the ultimate effect, `live()` would seem to be a feature subset of `livequery()`. But in fact `live()` doesn't actually do anything `livequery()` does. It just appears that way on the surface. :o)
patrick dw
You shouldn't need to use livequery if you upgrade the version of jQuery that you are using. This will save an extra download on each page.
Daniel Dyson
@Daniel Dyson could you tell me how to do it without using livequery ?
mcgrailm