Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .append() function

Tags:

jquery

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!

like image 437
Misha Moroshko Avatar asked Jan 20 '26 01:01

Misha Moroshko


2 Answers

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.

like image 76
richardtallent Avatar answered Jan 21 '26 18:01

richardtallent


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.

like image 31
RoToRa Avatar answered Jan 21 '26 19:01

RoToRa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!