Appending a DOM element twice (jQuery)

后端 未结 5 1885
走了就别回头了
走了就别回头了 2021-02-19 22:39

Can someone explain why the following snippet does not add to both #a and #b?

HTML:

5条回答
  •  孤独总比滥情好
    2021-02-19 23:03

    You need to create a new instance every single time you want to append to the DOM.

    Otherwise it refers to the same instance which was already appended.

    Remove the $ symbol preceding the new div to be added as that evaluates to a jQuery object and has the limitations as above stated. or clone the element.

    $(function(){
        var foo = "HI";
        $("#a").append(foo);
        $("#b").append(foo);
    });
    

    Check Fiddle

提交回复
热议问题