Jeff Ricks
Jeff Ricks

Reputation: 33

jQuery .append() produced out of order html elements. Why?

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?

Upvotes: 3

Views: 2119

Answers (2)

bobjoe
bobjoe

Reputation: 673

jQuery is creating a node whether the closing tag is explicitly specified or not and $("#container").append( '<div>' ); and $("#container").append( '<p>' );

What you need to do is either append to the new elements

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

or append the html together in one statement.

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

Upvotes: 3

Alnitak
Alnitak

Reputation: 339786

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');

Upvotes: 2

Related Questions