I want to send a list of properties to a function that will temporarily disable (via comments) those properties. The purpose is similar to what is accomplished by Chrome Dev Tools when inspecting the style of an element, except that the user will not check/uncheck boxes, instead, the action will be performed by JavaScript.
function disableProperties(el, properties) {
var property; // property value pair
var cssStr = el.style.cssText.replace(/; /g, ";");
for (let i = 0; i < properties.length; i++) {
property = properties[i] + ": " + eval("el.style." + properties[i]) + ";";
cssStr = cssStr.replace(property, "/* " + property + " */");
}
el.setAttribute("style", cssStr);
}
function restoreProperties(el, properties) {
var outHtml = el.outerHTML;
var key = 'style="';
var idx1 = outHtml.indexOf(key) + key.length;
var idx2 = outHtml.indexOf('"', idx1);
var style = outHtml.substring(idx1, idx2);
for (let i = 0; i < properties.length; i++) {
str = "/* " + properties[i];
let a = style.indexOf(str);
let b = style.indexOf(" */", a + a.length) + 3;
let comment = style.substring(a, b);
let property = (comment).replace("/*", "").replace("*/", "");
style = style.replace(comment, property);
}
el.style.cssText = style;
}
When elements are created, their style is embedded in the HTML instead of external CSS files. It is important that the properties are only temporarily disabled; their earlier values must be preserved.
UPDATE:
I thought my comment code was not working because I was trying to retrieve the comment by asking for el.style.cssText; however, the comment was only available through outerHTML.
The code below is functional, but I'm sure that could be cleaned up. If you have suggestions on how I can improve this code, please advise. Here is a fiddle to demonstrate one example of how I am using the code.