1

I want to copy some CSS styles form one DIV, to another DIV.

  1. Click on the "ONE" DIV

  2. Then jQuery read list of CSS properties from ARRAY

  3. Then copy these properties from DIV "ONE" to DIV "TWO".

This is my attempt, but it does not work. What's wrong with it?

"JsFiddle Example".

HTML

 <div class="one">Click HERE on this DIV, to TRANSFER CSS properties From this ONE</div>
 <div class="two">To this TWO</div>

CSS

* {
   background-color:gray;
}
.one {
   color: red;
   font-size:12px;
   width: 100px;
   height: 100px;
   background-color: white;
   margin: 20px;
   padding: 20px;
   font-weight: bold;
}
.two {
   font-size:20px;
   color: blue;
   width: 200px;
   height: 200px;
   background-color: yellow;
   margin: 20px;
   padding: 20px;
}

jQuery

 $(document).ready(function(){
     $("div.one").click(function(){
         var $array = ['color','width','height', 'background-color', 'font-weight', 'font-size'];
         $(this).each( $array , function(item, value){
             $("div.two").css(value, $(this).css(value));
         });
     });
 });
0

1 Answer 1

4
  1. Select jQuery at the left panel of JSFiddle.
  2. Use $.each(array, fn) instead of $().each(array, fn).
  3. Store $(this) in a variable, eg $this = $(this). Inside the loop, this refers to the array element, not to the DOM element which is clicked.
  4. (non-critical) Do not prefix non-jQuery objects with a $.

Demo: http://jsfiddle.net/meU9M/2/

$(document).ready(function(){
    $("div.one").click(function(){
        var array = ['color','width','height', 'background-color', 'font-weight', 'font-size'];
        var $this = $(this);
        $.each( array , function(item, value) {
            $("div.two").css(value, $this.css(value));
        });
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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.