2

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?

4 Answers 4

4
$(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.

Sign up to request clarification or add additional context in comments.

Comments

1
$("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.

Comments

1

Try:

$(".addLink").click(function() {
    var clone = $(this).parent().next("div.link").clone();
    $(this).closest(".group").append(clone);
});

1 Comment

$(this).next()... should be $(this).parent().next() to traverse to the <div class="link">
0

Try .parents()

$('.addlink').click(function(){
   var parent = $(this).parents('div.group');
   parent.children(':last').clone().appendTo(parent);
});

1 Comment

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: api.jquery.com/closest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.