23

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');
});
mcgrailm
  • 17,469
  • 22
  • 83
  • 129

3 Answers3

24

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
  • 34,973
  • 19
  • 109
  • 214
  • so this is a plugin that needs to be included ? – mcgrailm Oct 01 '10 at 15:00
  • 1
    +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. – user113716 Oct 01 '10 at 15:02
  • @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 Oct 01 '10 at 15:09
  • @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) – user113716 Oct 01 '10 at 15:14
  • 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 Oct 01 '10 at 15:16
  • 7
    @Daniel Dyson could you tell me how to do it without using livequery ? – mcgrailm Oct 01 '10 at 15:20
0

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
  • 74,352
  • 26
  • 153
  • 180
  • hoping I can find something that will cover them all but this may be the only way – mcgrailm Oct 01 '10 at 14:45
  • @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 Oct 01 '10 at 14:53
0

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

yfeldblum
  • 65,165
  • 12
  • 129
  • 169