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
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);
.html();
does 1 of two things. It either retrieves the HTML in the element, or is sets it if there is an argument. When it sets it, it completely overwrites whatever was there.
Take this slightly changed example where you can see easier the effects of using .html()
. Notice that Hello World 1
, and This is awesome 1
is not found in the div.
var Container = $('#prop');
Container.html('<p>Hello World 1</p>');
Container.append('<p>This is awesome 1</p>');
Container.html('<p>Hello World 2</p>');
Container.append('<p>This is awesome 2</p>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="prop"></div>
It work something like this :
html() will replace the innerHTML of the element.
append() will append new HTML to the end of existing elements.
<script type="text/javascript">
var Container = $('#prop');
/* Step 1 : Setting the Hello World in a div containing id #prop */
Container.html('<p>Hello World</p>');
/* Step 2 : Appending the This is awesome in the same div */
Container.append('<p>This is awesome</p>');
/* Step 3 : Setting the Hello World in a div containing id #prop (overiding the previous value) */
Container.html('<p>Hello World</p>');
/* Step 4 : Appending the This is awesome in the same div */
Container.append('<p>This is awesome</p>');
</script>
This is because, html() will override the old html content and put new content and append() will append the content.
Container.html('<p>Hello World</p>');
Container.append('<p>This is awesome</p>');
Container.html('<p>Hello World</p>');
// this line override previous html
Container.append('<p>This is awesome</p>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With