How can I check my Image object type?

If I write something like this:

var img = $(new Image()).attr('src', image.src);

      

How can I check later if the img var is an image and not something else?

+2


source to share


3 answers


 if ( img.is('img') ){

 }

      

for safety. I might be tempted to re-include var in jQuery, just you can change img to dom node or whatever ...



if ( $(img).is('img') ){

}

      

+6


source


img.filter('img')

      



If it returns something, then it's an image.

+1


source


You should avoid explicit type checking.

Use polymorphism to choose what to do with images and what to do with other objects.

var img = $(new Image())(...);
img.process = function(){ ... do whatever images need ... };
objs.push( img );

var txt = new Text();
txt.process = function(){ .. do text processing, spellcheck, ... };
objs.push( txt );

...

objs.each( o ) { o.process(); }

      

-1


source







All Articles