0

I want to apply some css using jquery to for example $('#btn').('color','red');

but the problem is that is not working for my next new added element, #btn. It work only to my existed element.

I use

$('#btn').on(function(){
   $(this).css('color','red');
});

but no luck

  • 1
    you cannot do it like it... any dom manipulation have to be done once the element is created... delegation using `on` is specific to event handling ... it cannot be used for dom manipulation – Arun P Johny Oct 06 '13 at 11:08
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Patsy Issa Oct 06 '13 at 11:09
  • You really should **[research](https://www.google.com.lb/search?q=bind+on+dynamic+element&oq=bind+on+dynamic+element&aqs=chrome..69i57.4424j0&sourceid=chrome&espvd=210&es_sm=93&ie=UTF-8)** before asking a question. – Patsy Issa Oct 06 '13 at 11:09
  • 1
    Just to clarify - because it sounds like you are using `#btn` more than once - **ID's should be unique!** Expected behaviour should be that `$('#btn')` selects a single element - the first it encounters. Perhaps try selecting by class name: `$('.myBtn')`... – Emissary Oct 06 '13 at 11:26

2 Answers2

0

You can use .livequery() plugin

e.g.

$('#btn').livequery(function() {
  $(this).css('color','red');
});

Hope that helps

Thanks

Anuj Aneja
  • 1,273
  • 11
  • 13
0

You might want to look into DOM4 Mutation Observers (W3C Working Draft). They can be used to get notified if the DOM is changed, so you can work on the newly inserted nodes for example. Also check out the Mutation Summary library. However, not all browsers do support this feature yet.

If this seems overkill for your use case, try setting the CSS before inserting anything or firing a custom event after insertion (e.g. using .trigger()).

Wolfram
  • 7,879
  • 3
  • 39
  • 62