tags:

views:

73

answers:

3

Why this

$("#mydiv").append("<ul>");
$("#mydiv").append("<li>Hello</li>");
$("#mydiv").append("</ul>");
alert($("#mydiv").html());

produces

<ul></ul><li>Hello</li>

and not

<ul><li>Hello</li></ul>

?

Thanks!

+6  A: 

Append() appends DOM nodes, not HTML tags (i.e., it's an object append, not a string append).

When you append <ul>, you are creating an entire UL node, with both start and end tags. The </ul> call is ignored.

richardtallent
Better say *HTML tags* instead of *HTML elements*.
Gumbo
Thanks, corrected.
richardtallent
Strictly not every HTML element is a tag. You can append a TextNode that is not :-)
Juriy
+2  A: 

Because you can't append the unfinished pieces of HTML, you always append the element. For your case you have do either

$("#mydiv").append("<ul></ul>");
$("#mydiv ul").append("<li>Hello</li>");

or

$("#mydiv").append("<ul><li>Hello</li></ul>");
Juriy
+1  A: 

Because the browser needs to (re)build its DOM after each append. It can't know that a closing tag will come later, and an opening tag by itself is invalid, so error correction kicks in which in this case closes the unclosed element.

This is one of the reasons why innerHtml and things that rely on it (such as jQuery's append method) are not reliable and should be avoided when possible.

RoToRa
To be clear, append only relies on innerHtml if you pass it HTML string fragments. append itself appends a DOM node; if you pass in a string of HTML, it uses innerHTML to create a DOM node to then append as such.
Antonio Salazar Cardozo