Appending a DOM element twice (jQuery)

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

    Because using append actually moves the element. So your code was moving $foo into the document at #a, then moving it from #a to #b. You could clone it instead like this for your desired affect - this way it is appending a clone rather than the initial element:

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

    You could also append the html from $foo, which would just take a copy of the dom within it rather than the element itself:

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

    The above examples are assuming you have a more complicated scenario where $foo isn't just a jQuery object created from a string... more likely it is created from an element in your DOM.

    If it is in fact just simply created this way and for this purpose... there is no reason at all to create that jQuery object to begin with, you could simply append the string itself ("HI") directly, like:

    var foo = "HI";
    $("#a").append(foo);
    //...
    

提交回复
热议问题