Why is jQuery html() method adding content to a paragraph instead of replacing it?

Viewed 56

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>

2 Answers

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:

<p id="pContainer">
    </p><div>paragraph text remains</div>
<p></p>

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:

Paragraphs are block-level elements, and notably will automatically close if another block-level element is parsed before the closing </p> tag.

(In contrast, having a <div> inside another <div> is perfectly valid.)

The main problem is invalid html markup, as CertainPerformance answered before. It will be better to use some tools to prevent including incompatible elements into other.

Most simplest way to do it - use online w3c html markup validator. https://validator.w3.org/

Related