views:

115

answers:

3

If I write something like this:

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

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

+1  A: 
img.filter('img')

If this returns something then it is an image.

Daniel Moura
+4  A: 
 if ( img.is('img') ){

 }

for safety I may be tempted to wrap the var in jQuery again just incase you may have changed the img to a dom node or something else...

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

}
redsquare
Is there a pure Javascript way to do this?
vsync
redsquare
A: 

You should avoid explicit type checking.

Use polymorphism to select what has to be done with images, and what has to be done 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(); }
xtofl
I'm using some gallery code and its an ugly code. sometimes img means Image object, sometimes its just an html code (flash EMBED or something) and it should only run some code i've written if img == Image object.
vsync