'How can I use jQuery line by line

I want to display comments line by line in a div but the div is closing first and after that the comments are listing.

if (comments.num_replies > 0) {
    $("#showComment").append(`<div id="replyContainer${comments.comment_id}" class="replyContainer">`);

    comments.comment_replies.forEach((replies) => {
        $("#showComment").append(`
            <div class="img-comment reply">
                <img src="${home_url}img/user.png">
                <div class="m-2 p-3 ">

                    <div class="user-date"><p class="username">@${replies.replier_username}</p><p class="date">${replies.dates}</p></div>
                    <p class="comment_content">${replies.reply_comment_content.replace(/\n/g, "<br>")}</p>
                </div>
            </div>
        `)
    });

    $("#showComment").append(`</div>`);
}


Solution 1:[1]

You can try something like this

if (comments.num_replies > 0) {
    let replies = comments.comment_replies.map((replies) => (
        `<div class="img-comment reply">
            <img src="${home_url}img/user.png">
            <div class="m-2 p-3 ">

                <div class="user-date"><p class="username">@${replies.replier_username}</p><p class="date">${replies.dates}</p></div>
                <p class="comment_content">${replies.reply_comment_content.replace(/\n/g, "<br>")}</p>
            </div>
        </div>`
    ));

    $("#showComment").append(`<div id="replyContainer${comments.comment_id}" class="replyContainer">${replies.join('')}</div>`);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ruleboy21