Alvaro
Alvaro

Reputation: 41595

How to wrap an image?

I don't understand very well this code:

var img = $('<img/>', {class: "photo", src: photo.url_n, width: wt, height: ht}).css("margin", border + "px");

It seems to create an image tag: <img src="" class="photo" ... />. I just want to wrap it with a link: <a href="#aaaa"></a>

But I am trying this and it doesn't work:

$(img).wrap('<a></a>');

I have also tried just:

img.wrap('<a></a>');

Finally the code add the img to another element like this:

d_row.append(img);

Upvotes: 1

Views: 1769

Answers (3)

Blazemonger
Blazemonger

Reputation: 92893

First: since img is created as a jQuery object, you don't need to write $(img) and wrap it in a jQuery object again. Just img will suffice.

Second: if img hasn't been appended to the document yet, then you can't modify it in-place with wrap().

Third: wrap() is designed to return the contents of the wrapped object, not the wrapper itself. You need to call parent() to get that.

Try:

img = img.wrap('<a>').parent();

(you don't need the closing </a>, jQuery will generate it automatically)

http://jsfiddle.net/TMeP6/

However: since img is no longer an image, the variable name img is inaccurate and potentially confusing. I would create a new variable name (a_img or something) and store it in that instead:

a_img = img.wrap('<a>').parent();

Upvotes: 1

Simon Edstr&#246;m
Simon Edstr&#246;m

Reputation: 6619

Wrap it after you have append it to the DOM and it should work:

http://jsfiddle.net/5Es6S/

Upvotes: 0

ninja
ninja

Reputation: 2263

d_row.append('<a>'+img+'</a>');

Or do you need more control?

Upvotes: 0

Related Questions