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.
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.
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
}
Try to copy every CSS-properties like this:
$("#target").css("border", $("#source").css("border"));
$("#target").css("background", $("#source").css("background"));
#source {
background-color: #dfeacb !important;
color: #bbae4e !important;
border: 1px solid green !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textArea id="source">Hello world!</textArea>
<textArea id="target">Hello world!</textArea>
Why not? you can create the dictionary that may consists of all properties.
it will automatically inherit the CSS..
– Kasturi Dec 20 '10 at 20:12would they? - because everyone validates their code, so they would have already found the error ;-)