Reputation: 148744
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
.
Upvotes: 32
Views: 49869
Reputation: 337733
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.
Upvotes: 31
Reputation: 547
If you just want the CSS, you can do the following:
let cssText = document.defaultView.getComputedStyle( $("#elementID"), "").cssText;
Then you can apply that to any new element.
Upvotes: 0
Reputation: 31
Try using this:
document.getElementById("spn2").style = document.getElementById("spn1").style;
Upvotes: 3
Reputation: 4281
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
Upvotes: 8
Reputation: 140182
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.
Upvotes: 2
Reputation: 3012
Why not applying whatever rules to both elements at the time?
Something like:
$('spn1','spn2').css({color: 'red'});
You could use multiple selectors http://api.jquery.com/multiple-selector/
Upvotes: -1
Reputation: 26163
Is there a reason you're not simply doing .clone(true)?
http://jsfiddle.net/johncmolyneux/6Fz84/
This example copies inline and class styles, but not id styles (which could be very useful).
Upvotes: 0
Reputation: 282
<div style='background-color:red; display:hidden' id='template'>
<span>Something</span>
</div>
var replica=$('#template').clone();
replica
.removeAttr('id')
.css('display', 'block')
.find('span').text('Whatever');
replica.appendTo('#container');
Upvotes: 0
Reputation: 66693
UPDATE
Check this fiddle: http://jsfiddle.net/9BJ5y/
Better idea would be clone spn1 and replace spn2 with it.
i.e. something like:
var x = $('#spn2').html();
$('#spn2').replaceWith($('#spn1').clone().html(x).attr('id', 'spn2'));
Upvotes: 0