Set / Copy javascript computed style from one element to another
Update:
As @icl7126 suggested, here is a shorter version for practically the same usage.
good thing to remember that this code would not run on most/older browser if not pre-compiled.
Original (ES 2017):
function copyNodeStyle(sourceNode, targetNode) {
const computedStyle = window.getComputedStyle(sourceNode);
Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
}
Precompiled (ES 5):
function copyNodeStyle(sourceNode, targetNode) {
var computedStyle = window.getComputedStyle(sourceNode);
Array.from(computedStyle).forEach(function (key) {
return targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key));
});
}
#original answer posted on Nov '13. CSS variables were not supported back then. (first introduces on firefox on Jul 2014)
#Thats it! I got it :)
Iv'e seen that lots of people view this question,
So below is more detailed and clean code.
var copyComputedStyle = function(from,to){
var computed_style_object = false;
//trying to figure out which style object we need to use depense on the browser support
//so we try until we have one
computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);
//if the browser dose not support both methods we will return null
if(!computed_style_object) return null;
var stylePropertyValid = function(name,value){
//checking that the value is not a undefined
return typeof value !== 'undefined' &&
//checking that the value is not a object
typeof value !== 'object' &&
//checking that the value is not a function
typeof value !== 'function' &&
//checking that we dosent have empty string
value.length > 0 &&
//checking that the property is not int index ( happens on some browser
value != parseInt(value)
};
//we iterating the computed style object and compy the style props and the values
for(property in computed_style_object)
{
//checking if the property and value we get are valid sinse browser have different implementations
if(stylePropertyValid(property,computed_style_object[property]))
{
//applying the style property to the target element
to.style[property] = computed_style_object[property];
}
}
};
How to copy all user provided styles from one object to another
Try something like this:
function ApplyStyles(select, span) {
var select = document.querySelector(select);
var span = document.querySelector(span);
var sheets = document.styleSheets;
for(var i = 0; i < sheets.length; i++) {
var rules = sheets[i].cssRules || sheets[i].rules;
for(var r = 0; r < rules.length; r++) {
var rule = rules[r];
var selectorText = rule.selectorText;
if(document.querySelector(selectorText) == select){
for(var l = 0; l < rule.style.length; l++){
span.style[rule.style[l]] = rule.style[rule.style[l]];
}
}
}
}
}
Then use the function like this:
ApplyStyles("#selection", "#span");
Here's a JSFiddle for example: https://jsfiddle.net/rsLnaw56/2/
How this works is it finds all external styles applied to the select
element and applies it to the span
element.
How to copy all CSS style from one DOM to another?
If you know which <style>
tags are being used to style the div
, you can copy the contents of those into new style tags over in the new window. However, that won't include styles directly on the div
itself.
White a bit more manual, the getComputedStyle function can give the current styling of the element, which you can then apply over in the new window. If there are children in the div
you're copying, you'll have to do this recursively or resolve common styles into a generated style sheet.
There are examples in the linked page, but I'll copy it here:
// print one or all of the style properties on the element
function dumpComputedStyles(elem,prop) {
var cs = window.getComputedStyle(elem,null);
if (prop) {
console.log(prop+" : "+cs.getPropertyValue(prop));
return;
}
var len = cs.length;
for (var i=0;i<len;i++) {
var style = cs[i];
console.log(style+" : "+cs.getPropertyValue(style));
}
}
How can I grab all css styles of an element?
UPDATE: As @tank answers below, Chrome version 77 added "Copy Styles" when you right-click on an element in the devtools inspector.
Using Javascript worked best for me. Here's how I did it:
- Open Chrome DevTools console.
Paste this
dumpCSSText
function from this stack overflow answer into the console, and hitEnter
:function dumpCSSText(element){
var s = '';
var o = getComputedStyle(element);
for(var i = 0; i < o.length; i++){
s+=o[i] + ':' + o.getPropertyValue(o[i])+';';
}
return s;
}When using Chrome, you can inspect an element and access it in the console with the
$0
variable. Chrome also has acopy
command, so use this command to copy ALL the css of the inspected element:copy(dumpCSSText($0));
Paste your CSS wherever you like! /p>
Copying specific styles from one element to another
.html()
doesn't include inline styles at all. You need to use the jQuery .css()
function;
$(".target_elements").css({top: $("someElement").offset().top, left: $("someElement").offset().left});
And since .offset()
returns a {top: ..., left: ...}
object, you can write the above more compactly as:
$(".target_elements").css($("someElement").offset());
How can I programmatically copy all of the style attributes from one DOM element to another
Have you tried cloneNode
? It can copy the element and all of its children in one fell swoop.
http://www.w3schools.com/dom/met_element_clonenode.asp
JavaScript & copy style
eval('oRow.cells[1].style.'+strAttribute)
Never use eval
like this(*). In JavaScript you can access a property whose name is stored in a string using square brackets. object.plop
is the same as object['plop']
:
to.style[name]= from.style[name];
(*: never use eval
at all if you can help it. There are only a few very specific and rare occasions you need it.)
Is there any way to loop over the style elements
The style
object is supposed to support the DOM Level 2 CSS CSSStyleDeclaration
interface. You could loop over the rules and apply them to another element like this:
for (var i= from.style.length; i-->0;) {
var name= from.style[i];
to.style.setProperty(name,
from.style.getPropertyValue(name),
priority= from.style.getPropertyPriority(name)
);
}
in IE?
No, IE does not support the whole CSSStyleDeclaration interface and the above won't work. However there is a simpler way not involving looping that will work on IE and the other browsers too:
to.style.cssText= from.style.cssText;
As simple as that! IE doesn't quite preserve the CSS text the way it should, but the difference doesn't matter for simple inline style copying.
However, as Pikrass said (+1), if you are copying a whole element and not just the styles, cloneNode
is by far the most elegant way to do that.
Related Topics
JavaScript - Loading/Busy Indicator or Transparent Div Over Page on Event Click
Get All CSS Root Variables in Array Using JavaScript and Change the Values
React Native Flexbox - How to Do Percentages || Columns || Responsive || Grid etc
Make the on Scroll Growing <Path> to Dashed Line
Capture/Save/Export an Image with CSS Filter Effects Applied
How to Get the Opacity of an Element Using JavaScript
Dynamically Changing Stylesheet Path Not Working in Ie and Firefox
Highcharts: Make the Legend Symbol a Square or Rectangle
How to Properly Escape Attribute Values in CSS/Js Attribute Selector [Attr=Value]
Customize Ng-Repeat in Angularjs for Every Nth Element
How to Show the Child Div on Mouse Hover of Parent Div
Hiding Div If Using Mobile Browser
Modify Pseudo-Element :After's Width Using JavaScript
How to Style Canvas Elements with CSS
How to Create and Apply CSS to JavaScript Alert
How to Change the Label Size of a Material UI Textfield
Kendo Chart Legend:Label at Left, Color at Right
How to Change Url in Browser Without Navigating Away from Page