tags:

views:

83

answers:

4

Here is my DOM:

    <div class="group">
        <div class="comment">
            <button class="addLink">Add link</button>
        </div>

        <div class="link">
            <button class="removeLink">Remove link</button>
        </div>
    </div>

I wanna click on the button.addLink and it will copy the div.link and append it as last child in div.group.

i started out with this code but got stuck.

 $(this).parent().parent().children(':last').clone().appendTo();

i dont know how to write appendTo. cause i want it to be appended to div.group but i cant just type it as 'div.group' cause there will be a lot of other div.group so i have to select it from a relational point of view.

could someone help me out here?

+1  A: 
$(this).parent().parent().children(':last').clone().appendTo($(this).parent().parent());

Or a bit nicer:

var $parent = $(this).parent().parent();
$parent.children(':last').clone().appendTo($parent);

appendTo() accepts a parameter as target where the elements should be appended to.

You should read the API documentation, it is well explained.

Felix Kling
+1  A: 

Try:

$(".addLink").click(function() {
    var clone = $(this).parent().next("div.link").clone();
    $(this).closest(".group").append(clone);
});
karim79
`$(this).next()...` should be `$(this).parent().next()` to traverse to the `<div class="link">`
Russ Cam
@Russ - you're right, missed that. Fixed, thanks.
karim79
@karim79 - No probs :)
Russ Cam
+1  A: 
$("button.addLink").click(function() {
    var self = $(this);
    var linkDiv = self.parent().next().clone();
    self.parent().parent().append(linkDiv);    
});

Here's a Working Demo. Click on the Preview button and try the code out.

Russ Cam
A: 

Try .parents()

$('.addlink').click(function(){
   var parent = $(this).parents('div.group');
   parent.children(':last').clone().appendTo(parent);
});
Reigel
`parents` can deliver more than one element. It also traverses up to the root node. karim79's approach with `closest` is much better in this case, see `parents` vs `closest` here: http://api.jquery.com/closest/
Felix Kling