Search code examples
javascriptjqueryhtmlcssclone

Is it possible to change the clone and the original element at the same time? - jQuery


I have an element with a clone inside a div parent. I want to click on clone and change css of this clone and its original element. But at same time if at first i click on original element I want to change the original elment and its clone.

Is possible ?

HTML

<div id="parent">
  <div class="hello">
  Hello
  </div>
</div>

CSS

.hello {
  width: 100px;
  height: 100px;
  color: #fff;
  background-color: #000;
  margin: 10px;
}

JAVASCRIPT

$('.hello').clone().appendTo('#parent');
$('.hello').on('click',function(){
    $(this).css('background-color','red');
});

Here jsfiddle: https://jsfiddle.net/vcyLkdas/

$('.hello').clone().appendTo('#parent');

$('.hello').on('click',function(){
	$(this).css('background-color','red');
});
.hello {
  width: 100px;
  height: 100px;
  color: #fff;
  background-color: #000;
  margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="parent">
<div class="hello">
Ciao
</div>
</div>


Solution

  • Replace $(this) with $(".hello") inside your handler.

    $(".hello").clone().appendTo("#parent");
    
    $(".hello").on("click", function () {
      $(".hello").css("background-color", "red");
    });
    .hello {
      width: 100px;
      height: 100px;
      color: #fff;
      background-color: #000;
      margin: 10px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="parent">
      <div class="hello">
        Ciao
      </div>
    </div>