Ankur Verma
Ankur Verma

Reputation: 5933

Adding a class to element whenever an element is added to DOM

I have following code in document.ready() as :

$(document).ready(function(){

   $('img').addClass('myClass');

});

Now this code works fine if I loads all the images at once, then this function adds the myClass to them(all img's). But what happens here is that whenever a new element with tag img like <img...../> is added in the DOM (via ajax or javascript), class to it does not gets added.. is it a limitation of JQuery or it provides this via some plugin or api,or we have to do it manually.

I want whenever a new img is added in DOM its class would set to myClass,

PS Right now I used setTimeout() like this to call a function after 2 secs to add classes to my images as :

setTimeout(function(){
  $('img').addClass('actAsButton');
},2000);

But is this the right way of doing, in fact this code also fails if we adds any new in DOM after 2 secs for that to happen I can use setInterval instead but that is quite costly in terms of memory usage.Please shed some light..

Upvotes: 1

Views: 79

Answers (3)

Vikash Pandey
Vikash Pandey

Reputation: 68

In your case the addClass is not working because the img element was not there when $(document).ready() was fired. S0, you should use following code for that.

$('img').live('load', function () {
    $('img').addClass('actAsButton');
});

Upvotes: 0

Wesley
Wesley

Reputation: 2264

$(document).on('img', 'load', function() {
    $(this).addClass('actAsButton');
});

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

$('img').load(function() {
  $(this).addClass('actAsButton');
})

Upvotes: 1

Related Questions