views:

40

answers:

3

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>
A: 

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')
meder
Great, thanks!!
Vincent
+3  A: 

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 />') );
patrick dw
A: 

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

Tom