1

JQuery .append () produced html elements that are out of order. Why?

 2 years ago
source link: https://www.codesd.com/item/jquery-append-produced-html-elements-that-are-out-of-order-why.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JQuery .append () produced html elements that are out of order. Why?

advertisements

My html contains this

<div id="container"></div>

and when I do this in javascript

$("#container").append( '<div>' );
$("#container").append( '<p>' );
$("#container").append( 'test content' );
$("#container").append( '</p>' );
$("#container").append( '</div>' );

it produces this in the browser

<div id="container">
    <div></div>
    <p></p>
    "test content"
    <p></p>
</div>

instead of this

<div id="container">
    <div>
    <p>
    "test content"
    </p>
    </div>
</div>

Why are the div and p elements terribly out of order? It's obviously appending extra </div> and </p> elements that my code doesn't append. Why?


The .append method can only insert complete HTML elements, not incomplete HTML fragments.

For elements that are not self closing this means that .append('<div>') will effectively append <div></div>. In fact, in this case the .append method doesn't really append the HTML at all, it'll just call document.createElement('div') and then append that newly created node to the designated parent.

An alternative way to produce your desired content would be:

$('<div>').append($('<p>').text('test content')).appendTo('#container');


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK