jQuery . what does $('<img/>') mean?

1.1k views Asked by At

Possible Duplicate:
What does the selector syntax mean in $( “<div/>” ).text( message )

I've searched but couldn't find any info on this... including the jQuery reference...

What does $('<img/>') mean in jQuery? I am familiar with $('img') only.

I have come across this code in this article: http://tympanus.net/codrops/2010/11/16/hover-slide-effect/

But in the code, when I replace one with the other, it stops working, so I guess they are not the same.

Also, the last piece of code:

.attr('src',$this.attr('src'));

what is it for? It seems redudant, but it also fails if I remove it. Can anyone elaborate on this?

Thanks

3

There are 3 answers

2
Denys Séguret On BEST ANSWER

$(anyHtmlCode) builds a jQuery wrapped set of elements built from the HTML you provide.

From the documentation :

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it has <tag ... > somewhere within the string). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements. You can perform any of the usual jQuery methods on this object

The line

$someElement.attr('src',$this.attr('src'));

sets the src of $someElement to be the same as those of $this.

0
Ashirvad On

$('<img/>') is creating a new image tag . it is similar to

document.createElement('img')
0
Mark On

$('<img />') actually creates a new img element and wraps it in a jQuery object, whereas $('img') selects all img elements on the page.

$('img').attr('src',$this.attr('src')) sets the first matched img element's src attribute.