jQuery Clone Question. (clone vs original)

Hello, Please look at the code where I put // here, my question is why does parent() function took place in left-well class rather than right-well class? Since they both have target5 and I thought clone() function send the copy of target5 to left-well and the original target5 should stay in right-well, so why does the color change only in left-well? thanks

<script>
  $(document).ready(function() {
    $("#target1").css("color", "red");
    $("#target1").prop("disabled", true);
    $("#target4").remove();
    $("#target2").appendTo("#right-well");
    $("#target5").clone().appendTo("#left-well");
    $("#target5").parent().css("background-color", "red");        // here 
    $("#right-well").children().css("color", "orange");
    $(".target:nth-child(2)").addClass("animated bounce"); 
  });
</script>

<!-- Only change code above this line. -->

<div class="container-fluid">
  <h3 class="text-primary text-center">jQuery Playground</h3>
  <div class="row">
    <div class="col-xs-6">
      <h4>#left-well</h4>
      <div class="well" id="left-well">
        <button class="btn btn-default target" id="target1">#target1</button>
        <button class="btn btn-default target" id="target2">#target2</button>
        <button class="btn btn-default target" id="target3">#target3</button>
      </div>
    </div>
    <div class="col-xs-6">
      <h4>#right-well</h4>
      <div class="well" id="right-well">
        <button class="btn btn-default target" id="target4">#target4</button>
        <button class="btn btn-default target" id="target5">#target5</button>
        <button class="btn btn-default target" id="target6">#target6</button>
      </div>
    </div>
  </div>
</div>

please look at the line 9

IDs are supposed to be unique, so from my experience I’d say it’s because javascript just select the first “target5” it encounters since there shouldn’t be two identical IDs

2 Likes

pretty much what @tommypepsi said. From the jQuery documentation:

Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.

http://api.jquery.com/clone/

1 Like

oh ok thanks so much. No wonder.
!

Thanks very much for the info and explanation

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

1 Like

Thank you for helping me with that .

1 Like