I need to be able to copy all of the CSS properties from an existing HTML element to DOM-defined element, except where CSS properties are already defined in an external stylesheet for the DOM element.
I have an external stylesheet:
#MyTargetElmnt { font-weight: bold }
This works perfectly for copying the all CSS properties:
objSource = document.getElementById('MySourceElmnt');
objCSS = window.getComputedStyle(objSource);
objTarget = document.createElement('div');
for (var i = 0; i < objCSS.length; i++) {
objTarget.style.setProperty(objCSS[i], objCSS.getPropertyValue(objCSS[i]));
}
objTarget.setProperty('id', 'MyTargetElmnt');
...but, if the source element has a style of font-weight: normal
, that's what will stick.
I think what I need is something like:
...
objTarget.setProperty('id', 'MyTargetElmnt');
for (var i = 0; i < objCSS.length; i++) {
if (!objTarget.style.getPropertyValue(objCSS[i]) && !objTarget.style.hasOwnProperty(objCSS[i])) {
objTarget.style.setProperty(objCSS[i], objCSS.getPropertyValue(objCSS[i]));
}
}
I'm stuck on what to put inside if ()
I dumped the objTarget.style
object into console.log
and it does not contain any of the CSS properties defined the stylesheet. style.getPropertyValue
is the same and I can't use getComputedStyle
on the target element for comparison because it will contain all of the computed styles that I want to copy from the source element (which will cause it to copy no styles at all).
How do I obtain the CSS properties from the external stylesheet for comparison?