1

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);
1
  • did you tried: $(img).wrap('<a />');? Mar 28, 2012 at 14:45

3 Answers 3

1

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();
0
0
d_row.append('<a>'+img+'</a>');

Or do you need more control?

0

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

http://jsfiddle.net/5Es6S/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.