JSFiddle - React, Tailwind, and code Playground
by mark087
HTML
<form id="styleForm" style="padding:20px" onsubmit="return styleFormHandler()">
<label for="style">style:</label>
<input id="styleName" type="text" value="background" name="style" required/>
<label for="styleValue">value:</label>
<input id="styleValue" type="text" value="#ff0000 !important" name="styleValue" required/>
<input type="submit" value="change styles">
</form>
<div id="container" style="background: #dedede; margin: 10px auto; padding: 20px; display: block; max-height: 900px; max-width: 100%; opacity: 1; visibility: visible; width: 700px; box-sizing: border-box;"></div>
JavaScript
var testEl = document.getElementById("container"),
styleName = document.getElementById("styleName"),
styleVal = document.getElementById("styleValue");
function setCssTextStyle(el, style, value) {
var result = el.style.cssText.match(new RegExp("(?:[;\\s]|^)(" +
style.replace("-", "\\-") + "\\s*:(.*?)(;|$))")),
idx;
if (result) {
idx = result.index + result[0].indexOf(result[1]);
el.style.cssText = el.style.cssText.substring(0, idx) +
style + ": " + value + ";" +
el.style.cssText.substring(idx + result[1].length);
} else {
el.style.cssText += " " + style + ": " + value + ";";
}
}
function showStyles(el) {
var styles = el.style.cssText.split(/\s*;\s*/)
len = styles.length;
el.innerHTML = '<b>CURRENT ELEMENT STYLES:</b></br/><ul>';
for (var i = 0; i < len; i++) {
if (styles[i]) {
el.innerHTML += "<li>" + styles[i] + ";</li>";
}
}
el.innerHTML += '</ul>';
}
window.styleFormHandler = function() {
if (styleName.value && styleVal.value) {
setCssTextStyle(testEl, styleName.value, styleVal.value);
showStyles(testEl);
}
return false;
};
showStyles(testEl);
document.body.appendChild(testEl);