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.
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”.
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.
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 .
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.
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 }
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