Clone style in jQuery?

Try using this:

document.getElementById("spn2").style = document.getElementById("spn1").style;

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.


jQuery doesn't have any direct facilities for doing this. You will have to use plain old JavaScript to find a cross-browser way to copy over the computed style of one element to another. This answer has an implementation for a potential solution.


Take a look at this thread: https://stackoverflow.com/a/6416527/541827
The idea is to copy all the style's properties from one item to another

Or just use the jquery.copycss.js plugin, the answer is based on.
Usage:

$('#some-element').copyCSS('#another-element');  // copy all styles
$('#some-element').copyCSS('#another-element', ['top', 'left']);  // copy just top and left
$('#some-element').copyCSS('#another-element', null, ['top', 'left']);  // copy everything except top and left

Tags:

Jquery