"); $("#mydiv").append("
  • Hello
  • "); $("#mydiv").append(""); alert($("#m...">

    JQuery.append () Function

    Why this

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

    produces

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

    but not

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

    ?

    Thanks!

    +2


    a source to share


    3 answers


    Because the browser needs to (re) build its DOM after every add. It cannot know that the closing tag will come later, and the opening tag itself is not valid, so the bug fix hits where the unclosed element is closed in this case.



    This is one reason why, innerHtml

    and things that rely on it (like the jQuery add method) are unreliable and should be avoided whenever possible.

    +2


    a source


    Append () adds DOM nodes, not HTML tags (i.e. adds an object, not a string).



    When you add <ul>

    , you create the entire UL node, with both start and end tags. The call is </ul>

    ignored.

    +7


    a source


    Since you cannot add unfinished HTML snippets, you always add an element. For your cause, you do either

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

    or

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

    +2


    a source







    All Articles