Clone style in jQuery?

To copy the explicit styling set on an element you can use this method:

let $original = $('#spn1');
let $target = $('#spn2');

$target
  .prop("style", $original.attr("style"))
  .addClass($original.attr("class"));
.foo { color: #F00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<span id="spn1" class="foo" style="background-color: #FF0;">Styled by default</span>
<span id="spn2">Plain by default</span>

Note that this will not copy the computed style of an element, i.e. style rules inherited from parent elements or global selectors.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)