Unexpected behavior of jQuery html () and append ()
So, I have a div created using regular HTML like this.
<div id="prop"></div>
And using jquery selector I insert 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 expect an exit like this.
Hello World
This is awesome
This is awesome
But the original conclusion
Hello World
This is awesome
I canβt understand why this is happening. Correct me if I ask something wrong. thanks in advance
html(String)will replace the innerHTML of the element with the passed string.
append(String)will add the passed string to the end of the element.
So, when you call html()on an element, the previous elements are overwritten. Your code is equivalent
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>');
HMTL, DOM. , DOM .
var elem = '<p>Hello World!</p><p>This is Awesome</p>';
$('#prop').html(elem);
.html(); . HTML , , . , , .
, .html(). , Hello World 1 This is awesome 1 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>:
html() innerHTML .
append() HTML .
<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>