Search code examples
jquerycloneelement

I cant't copy/clone html element in jQuery


I can't clone/copy element in DOM.

My code HTML:

<section class="_col-12 flexbox flex-column" id="580">
  <article class="flat-White">
  <img src="https://www.iana.org/_img/2013.1/rir-map.svg" class="campoNoticia img-fluid">
  <div class="campoNoticia p1em">
    <h1>Title</h1>
    <p>Parrafe</p>
   </div>
  </article>
</section>
<article>Article area</article>

My jQuery Code:

$(document).on("click",".campoNoticia", function(evt) {
    var $imgRute = $(this).closest('section').find('img').html();
    $("article").append($imgRute);
});

My jsFiddle:

https://jsfiddle.net/yt2hbrdn/24/


Solution

  • This is because the .html() will return the HTML inside the element on which it is called.

    For example, consider the following code:

    <div id="test"> Test HTML <div>
    

    And the JS:

    // This will return the inner HTML content of the div
    $("#test").html(); // Test HTML
    

    As mentioned above, it will not return the element. It will only return it's inner HTML.

    In your case, it's the img element and as you might already know, there is nothing to put inside the img element ever i.e. you never do something like this:

    <!-- This is not valid -->
    <img src="something"> Image </img>
    

    So, when you do this var $imgRute = $(this).closest('section').find('img').html(); the value of $imgRute will be an empty string and not the img element itself.

    I guess you want to do .clone() instead of .html().

    Here's what the documentation says about .clone():

    The .clone() method performs a deepcopy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.

    So, if you want to clone the img element, your code will be as follows:

    $(document).on("click", ".campoNoticia", function(evt) { 
        var $imgRute = $(this).closest('section').find('img').clone(); 
        $("article").append($imgRute); 
    });