2

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?

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

3

.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)).

Matt Bradley
  • 4,395
  • 1
  • 20
  • 13
0

Try this:

$(document).on("click", ".local", function(){
    $(this)
        .closest(".block")
        .css("background-color","yellow")
        .find("ul.items")
        .append( $("<li>")
            .attr("class","item")
            .html( $("<p>").html("added") );
        );
});

Example.

Please note that on() was added in jQuery 1.7.

We attach the click handler to any element with class local. When clicked, it will traverse up the DOM until it finds the closest element with class block. It sets it background color to yellow then selects its child ul with class items. It then appends the new li element. Meanwhile, we also set the li's class and text with jQuery.

Purag
  • 16,941
  • 4
  • 54
  • 75