Appending a DOM element twice (jQuery)

后端 未结 5 1884
走了就别回头了
走了就别回头了 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:07

    Try clone. This, as the name implies, will copy the $foo element and not move, like append will do.

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

    But, why not just use this?

    $("#a,#b").append($foo);
    

    This will also work :)

    Here's a demo for both these situations : http://jsfiddle.net/hungerpain/sCvs7/3/

提交回复
热议问题