Cannot load append () correctly

I have a problem with append, I think, to be honest, I don’t know where my problem is in the code, but I just can't get it to work. First I will show you my code, and then I will try my best to explain what my problem is.

$('.dynamic').append('<div class="clipboardContent"></div>').html(window[recentPerson].fullname + '<br><span style="color:lightgray; font-size:10pt">' + window[recentPerson].mail + '</span>');
$('.dynamic').append('<div class="clipboardContent">HI</div>');

So you can see two pieces of code here. The first is the one that I want to work, but does not. The second is simpler, but it works. My problem is that if I click on the button, it can create a div in the clipboardContent class with some text in it (this still works), but if I click again, it will not add a new one (but the second code does), Hopefully someone can explain to me why the first code only works once.

PS. If you have other questions or need more code / explanations for my problem, feel free to let me know.

+4
source share
2 answers

The problem is that the method append()returns the selected item. In your case, this is an element .dynamic. After adding, you install html()from .dynamic, which then overwrites div, added to append().

To accomplish what you need, you can create an element divseparately before adding:

$('<div />', {
    class: 'clipboardContent',
    html: window[recentPerson].fullname + '<br><span style="color: lightgray; font-size: 10pt">' + window[recentPerson].mail + '</span>'
}).appendTo('.dynamic');

Working example

Or you can save your current method and include HTML in the line you add:

$('.dynamic').append('<div class="clipboardContent">' + window[recentPerson].fullname + '<br><span style="color:lightgray; font-size:10pt">' + window[recentPerson].mail + '</span></div>');

, CSS style. , , , JS , .

+7

.append(), .html(), , .append()

$(".dynamic").append('<div class="clipboardContent">YOUR_CONTENT</div>');
0

Source: https://habr.com/ru/post/1627944/


All Articles