Dušan
Dušan

Reputation: 498

jquery append only appends in first element of list or shows error [object Object]

I have a variable var $deleteEl = $('<a class="upload_delete" href="#">Delete</a>'); which is a delete link that need to be created next to each uploaded image. html structure is next:

<ul id="thumb_galery">
    <li class="thumb">
        <img>
        <a class="upload_delete"></a>
    </li>
    <li class="thumb">
        <img>
        <a class="upload_delete"></a>
    </li>
</ul>

for every uploaded image, thumb with image is appended to thumb_galery

$(thumb_galery).append('<li id="thumb"><img src="img/success.jpg" alt="' + fileName + '"></li>');

i need to add delete link in the same li next to the image as provided in html structure.

If i append delete link like this

$(thumb).append($deleteEl);

it works great for first image uploaded, but for next images it only appends it to the first li with class thumb.

How can the delete link be appended in li for the next uploaded image?

The other solution i tried is to place a variable in the first append like this

$(thumb_galery).append('<li class="thumb"><img src="img/success.jpg" alt="' + fileName + '">' + $deleteEl + '</li>');

This creates the perfect html structure but instead of delete link it shows [object Object]

Upvotes: 0

Views: 827

Answers (2)

PSL
PSL

Reputation: 123739

You can directly append it like this, You should not have multiple elements with the same id.

http://jsfiddle.net/xq8f7/

var $deleteEl = $('<a>',{ 
    'class': "upload_delete",
    href: "#",
    text: "Delete"});
$('.thumb').append($deleteEl);  

Upvotes: 1

Ian
Ian

Reputation: 50905

Give the elements a unique id or use a class. And try:

var item = $('<li id="thumbX" class="thumb"><img src="img/success.jpg" alt="' + fileName + '"></li>');
item.append($deleteEl)
$(thumb_galery).append(item); 

Upvotes: 2

Related Questions