htoniv htoniv - 4 months ago 17
HTML Question

Unexpected behaviour of jQuery html() and append()

So here i am having a div created using normal HTML like this.

<div id="prop"></div>


And by using jquery selector i am inserting html elements dynamically like

var Container = $('#prop');
Container.html('<p>Hello World</p>');
Container.append('<p>This is awesome</p>');
Container.html('<p>Hello World</p>');
Container.append('<p>This is awesome</p>');


Here i am expecting the output like this.

Hello World

This is awesome

This is awesome


But the original output is

Hello World

This is awesome


I cant understand why it is coming like this. Correct me if i asked anything wrong. Thanks in advance

Answer

html(String) will replace the innerHTML of the element by passed string.

append(String) will append passed string to the end of element.

So, when you call html() on element, previous elements are overwritten. Your code is equivalent to

var Container = $('#prop');

// Do something here with innerHTML
// and next line will overwrite it
Container.html('<p>Hello World</p>');
Container.append('<p>This is awesome</p>');

I'll recommend to create HMTL first and then update it in DOM. This will be little faster as it has to interact with DOM only once.

var elem = '<p>Hello World!</p><p>This is Awesome</p>';
$('#prop').html(elem);