Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy all styles from one element to another

How can i get every styles (even inherited) from an element A to an element B ? in javascript or using jquery.

let's tell i have an element <p class="foo">...</p> and i append new element <div /> which would look like the same, except content.

like image 881
jney Avatar asked Dec 20 '10 20:12

jney


People also ask

How do I copy all elements in CSS?

First, hover over the element you want to copy. Then, right-click on it and choose the option “Inspect”. On the left side is the HTML DOM tree, and on the right side, the CSS styles of the selected element. Having the right element selected on the HTML DOM tree, right-click on it and choose “Copy” > “Copy styles”.

How do you copy an element style?

To copy a style from one element to another:Use the window. getComputedStyle() method to get an object of the element's styles. Assign the specific styles to the other element's style object.

How do you set a computed style?

To set or copy JavaScript computed style from one element to another, we can loop through each style and call the setProperty method to set the styles on the target element. to add a div and a section element. We define the copyNode function that takes the sourceNode and targetNode .


2 Answers

If you don't care about IE, then you can do this:

var p = document.getElementById("your_p_id");  var div = document.createElement("div");  div.innerHTML = "your div content";  div.style.cssText = document.defaultView.getComputedStyle(p, "").cssText;
#your_p_id {    color: #123124;    background-color: #decbda;  }
<textArea id="your_p_id">Hello world!</textArea>

This works for inline, embedded, and inherited styles.

EDIT: And by "don't care about IE," I of course meant "don't care about anything except Webkit."

UPDATE: This works in the current versions of Chrome(19), Safari(5), Firefox(12), and IE(9). It also works in older versions of some, such as IE8.

like image 139
sdleihssirhc Avatar answered Sep 22 '22 10:09

sdleihssirhc


Actually, sdleihssirhc's answer will not work on firefox as getComputedStyle(p, "").cssText will return an empty string, it's a longstanding and know bug: https://bugzilla.mozilla.org/show_bug.cgi?id=137687

The solution to also support Firefox is to iterate on getComputedStyle properties and create the CSS string manually:

var clonedNode = document.createElement("div"); const styles = window.getComputedStyle(node); if (styles.cssText !== '') {     clonedNode.style.cssText = styles.cssText; } else {     const cssText = Object.values(styles).reduce(         (css, propertyName) =>             `${css}${propertyName}:${styles.getPropertyValue(                 propertyName             )};`     );      clonedNode.style.cssText = cssText } 
like image 26
Thibaut Avatar answered Sep 26 '22 10:09

Thibaut