I would like to dynamically add/edit a property of the style attribute based on the user input. The user can give the Property Name and Property Value as a string. I would need to validate, if the given string is a valid property name/property value for the style attribute of an HTML element before applying.
Is there any way to achieve the above validation?
Is there any javascript function that can validate the given string for valid property name/property value or function that returns all valid properties/values for a particular property of the style attribute
The idea is applying the style and checking for its existence. This function can use some improvements but it works or at least demonstrates the concept.
function is_valid_css_prop(prop, value) {
var div = document.createElement("div");
document.body.appendChild(div)
div.style[prop] = value;
var obj = getComputedStyle(div);
var found = false;
for (var key in obj) {
if (key == prop && value == obj[key]) {
found = true;
break;
}
}
document.body.removeChild(div)
return found;
}
console.log(is_valid_css_prop("position", "above"));
console.log(is_valid_css_prop("position", "absolute"));