Reputation:
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.
Upvotes: 2
Views: 238
Reputation: 18078
Try this:
$(".myClass tr td:last-child").each(function() {
var $clone = $("#elementToClone").clone(false);
$clone.attr('id', $clone.attr('id') + $(this).attr('id')).appendTo(this);
});
untested
Upvotes: 0
Reputation: 195992
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..)
Upvotes: 3