简体   繁体   中英

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM