Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone style in jQuery?

Tags:

jquery

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.

like image 612
Royi Namir Avatar asked Jan 10 '12 15:01

Royi Namir


People also ask

What is clone method in jQuery?

jQuery clone() Method The clone() method makes a copy of selected elements, including child nodes, text and attributes.

How do you clone an object in jQuery?

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);

How do you clone in HTML?

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).

How do you replace an element with another in jQuery?

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.


1 Answers

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.

like image 122
Rory McCrossan Avatar answered Sep 28 '22 08:09

Rory McCrossan