tags:

views:

40

answers:

2

I want to create and append an item in jquery, while saving a reference to it.

 var buy = "<img src='img/buy-now.png' />";      
 var $buy = $(buy).appendTo("body");
 $buy.html("hello");

I was expecting something like the above to work. Any ideas?

+2  A: 

Yes, the variable $buy will save the reference of the element and the jQuery object.

Edit: $buy.html("hello"); will add "hello" inside the image tag, however it will be hidden on the screen since the image is being displayed.

digitalFresh
Uhhh. you're right. Oops. Thanks / Sorry.
Matrym
+4  A: 

In short, $buy is the object you've appended, you're just doing an invalid operation. <img /> is a self-closing tag, there is no HTML inside it, so .html("something") will have no effect.

If you meant to set the tooltip, use .attr(), like this:

$buy.attr('alt', 'hello');
Nick Craver