Search code examples
jqueryattributesappendcloneparent-child

add parent's id to appended clone's while appending renamed clones to multiple parents


Is it possible to clone a single element, append it to many elements, and add each new parent's respective id to each new respective clone's all on one line of jQuery?

I can clone and append, but I don't know how to grab the id of the element being appended to.

This is as far as I've gotten:

$(".myClass tr td:last-child").append($("#elementToClone").clone(false).attr('id',$(this).attr('id') + ?));

Where ? is where I'm lost.

Many thanks in advance!

Few-liners Welcome

Didn't know that could be a possibility, but 1 is better than 2 or 3. Few-liner can get a check until a 1 liner comes along.


Solution

  • If with parents id you mean the id of the td (and for some reason you want to avoid manual variable creations) then you can

    $(".myClass tr td:last-child").each(function(index, element) {
        $("#elementToClone").clone(false).attr('id', function(i, value) {
            return value + element.id;
        }).appendTo(element);
    });
    

    In regards to a single liner, the above can easily become

    $(".myClass tr td:last-child").each(function(index, element) {$("#elementToClone").clone(false).attr('id', function(i, value) {return value + element.id;}).appendTo(element);});
    

    Which is exactly the same code without the whitespace.. (not sure why you give gravity to it though..)