Search code examples
jqueryappendtoparents

parents and appendto don't work together?


jquery.parents and jquery.appendTo seem don't work together, for instance, I want to add a new element to the clicked button's parent's element only,

   $('.local').click(function(){

    var object = $(this);
    var parent = object.parents('.block').css({background:'yellow'});
    $('<li class="item"></li>').appendTo('.items',parent).html('\
        <p>added</p>\
    ');

    return false;
});

html,

<!-- block -->
<div class="block">

    <ul class="items"></ul>
    <ul class="menu">
        <a href="#" class="local">add</a>
    </ul>

</div>
<!-- block -->

<!-- block -->
<div class="block">

    <ul class="items"></ul>
    <ul class="menu">
        <a href="#" class="local">add</a>
    </ul>

</div>
<!-- block -->


<!-- block -->
<div class="block">

    <ul class="items"></ul>
    <ul class="menu">
        <a href="#" class="local">add</a>
    </ul>

</div>
<!-- block -->

so when I click the first add button. the added paragraph should be added to the first's add button's parent's element only but not other parents which have the same class name.

Here is the test page.

Can I fix it? Or I must have coded it wrong?


Solution

  • .appendTo() doesn't work that way. Try this:

      $('.local').click(function(){
    
        var object = $(this);
        var parent = object.parents('.block').css({background:'yellow'});
        $('<li class="item"></li>').appendTo($('.items',parent)).html('\
            <p>added</p>\
        ');
    
        return false;
    });
    

    Instead of .appendTo('.items',parent)), it should be .appendTo($('.items',parent)).