Vincent
Vincent

Reputation: 16216

JQuery wrap() problem

Why doesn't the following code wrap the image with <li> tags and what would be the best way to do this?

var i = new Image
i.src = '/images/image.jpeg'

$(i).wrap('<li />')
$('div').html(i)

produces:

<div><img src="/images/image.jpeg"></div>

instead desired:

<div><li><img src="/images/image.jpeg"></li></div>

Upvotes: 1

Views: 824

Answers (4)

Denes Papp
Denes Papp

Reputation: 3982

If you write

var i = new Image();
i.src = '/images/image.jpeg';

var li = $(i).wrap($('<li/>')).parent();   // since .wrap returns the inner element
$('<div/>').html(li)

then you get the proper structure:

enter image description here

Upvotes: 0

user113716
user113716

Reputation: 322502

Is there a reason you wouldn't just do this?

$('div').html('<li><img src="/images/image.jpeg" /></li>');

Please note that either way you are appending an <li> element to a <div> which is not technically correct.

The <li> should be a child of <ul> or <ol>.


EDIT:

Specific to the issue you were having, your code was correct, but you just needed to place the wrapped <img> inside the .html() call:

var i = new Image;
i.src = '/images/image.jpeg';

$('div').html( $(i).wrap('<li />') );

Upvotes: 3

tomsseisums
tomsseisums

Reputation: 13367

.html() overwrites all the content what's inside the element. So it removes that <li> over there.

Upvotes: 0

meder omuraliev
meder omuraliev

Reputation: 186562

i is a reference to the image. wrap doesn't change that. Can't you just generate the li then appendTo on the li?

i = new Image;
$('<li/>').append(i).appendTo('div')

Upvotes: 1

Related Questions