0

Using Is it possible to add "class" to dynamic elements. In the below example I have written it in document ready. I want to do it for elements which will be dynamically added to have the "class" name set to "someclassname"

$.find("input[type=text],select").addClass("someclassname");

I know we can use delegate method to add events for dynamic elements. But is it possible to add class name dynamically ?

I am doing below in my code to add "focus" event. But I want to set default class while the elements are dynamically rendered in the UI.

$( "form" ).on("focusin","input[type=text],select", function() {
  $(this).addClass('selected');
}).on("focusout","input[type=text],select", function() {
   $(this).removeClass('selected');
});
user2300875
  • 529
  • 1
  • 6
  • 20
  • MutationObserver.. check this http://stackoverflow.com/questions/16990573/how-to-bind-bootstrap-popover-on-dynamic-elements/16991216#16991216 – PSL Sep 06 '13 at 02:10
  • Do you want to add/remove classes in a `.delegate()` event? Or do you want to automatically add classes when more elements match the selector in the future? If that's what you want, it's probably easier to just add the classes when you create the elements. – CheeseWarlock Sep 06 '13 at 02:35

1 Answers1

0

You can use currentTarget property of the event object passed as a parameter to the event listener

$( "form" ).on("focusin","input[type=text],select", function(e) {
  $(e.currentTarget).addClass('selected');
}).on("focusout","input[type=text],select", function(e) {
   $(e.currentTarget).removeClass('selected');
});
enriquecastl
  • 840
  • 5
  • 10