Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get append() working in the right way

I am having a problem with append I think, to be honest I do not really know where my problem is in the code, but I just can not make it 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 what you can see here are two pieces of code. The first one is the one that I want to work but does not. The second one is more simple but does work. My problem is that if I click on a button it sould create a div in the class clipboardContent with some text in it (this still works), but if I click again It doesn't add a new one (But the second code does). I hope someone can explain to my why the first code only works one time.

PS. If you have some other questions or you need more code / explanation of my problem feel free to let me know.

like image 612
DrBruinbeer Avatar asked Mar 14 '23 08:03

DrBruinbeer


1 Answers

The issue you have is that the append() method returns the element originally selected. In your case this is the .dynamic element. After appending you are setting the html() of .dynamic which then overwrites the div you added in the append().

To do what you require you can create the div element separately before appending:

$('<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 could keep your current method and include the HTML in the string being appended:

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

Also, as a side-note, you should look to using CSS classes on your elements over inline style attributes. This way you can make all styling changes in a single place, instead of having to amend your JS files to affect style rules.

like image 84
Rory McCrossan Avatar answered Mar 25 '23 07:03

Rory McCrossan