Jai Gtz
Jai Gtz

Reputation: 65

Jquery append overwrite same element

I have problem to append to same element. The problem is i have 2 cases:

if (lastIndexOfUnderscore < 0){ //list priv (no parent)
        $("<a href='#' class='list-group-item'></a>").text(items.name).appendTo($div);
} else {
        $("<a href='#' class='list-group-item'></a>").text(items.name).appendTo($div);
}

I want the ui to be 'no parent' in one div and 'else' on other div.

I already try .clone() but still cant figure it.

Here is the code..https://jsfiddle.net/zofeqjm1/

Upvotes: 1

Views: 769

Answers (1)

Ibrahim Khan
Ibrahim Khan

Reputation: 20750

You can do it like following. Add a div with id = parentId if the item has parentId. If a div with parentId already exist then add the item to the div.

$.each(sample.item, function (i, items) {
    if (items.parentId) {
        if ($('#' + items.parentId).length) {
            $('#' + items.parentId).append('<a href=# class=list-group-item>' + items.name + '</a>');
        } else {
            $('.priv').append('<div id=' + items.parentId + '><a href=# class=list-group-item>' + items.name + '</a></div>');
        }
    } else { //list priv (no parent)
        $('.privList').append('<a href=# class=list-group-item>' + items.name + '</a>');
    }
});

DEMO

Upvotes: 2

Related Questions