I have a <span>
called spn1
, which has some style from inline + CSS file.
I have another <span>
called spn2
.
How can I clone spn1
's complete style into spn2
?
I want spn2
to look exactly (in style) like spn1
.
jQuery clone() Method The clone() method makes a copy of selected elements, including child nodes, text and attributes.
Syntax: // Create a clone of the object using the extend() method let newObj = jQuery. extend({}, obj); // Create a deep clone of the object using the deep parameter let newDeepObj = jQuery. extend(true, {}, obj);
The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Set the deep parameter to true if you also want to clone descendants (children).
We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With