Why is jQuery html() method, adding the string to the content of a <p>
tag instead of replacing it?
function refresh() {
$('#pContainer').html('<div>updated...</div>');
}
$(document).ready(function ($) {
window.setInterval(refresh, 3000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id='pContainer'>
<div>paragraph text remains</div>
</p>
In case of div
tag, the content are replaced:
function refresh() {
$('#divContainer').html('<div>updated...</div>');
}
$(document).ready(function ($) {
window.setInterval(refresh, 3000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<dic id='divContainer'>
<div>div text disappears</div>
</div>
Your HTML is not valid. A
<p>
cannot have a<div>
as a child. The browser has automatically attempted to correct your HTML and turns it into:As a result, when you assign to the HTML of the
#pContainer
, since the browser has moved the<div>
outside of the<p>
, the<div>
remains unaffected.As MDN puts it:
(In contrast, having a
<div>
inside another<div>
is perfectly valid.)