Camel case joins words without spaces, capitalizing each word after the first. In browser JavaScript, it lets you access multiword CSS style names through the element’s style property: CSS font-size becomes JavaScript fontSize. section 12.3.2
When working with style properties:
- Convert hyphenated CSS names such as background-color to camel case, such as backgroundColor, before accessing them as JavaScript properties. section 12.3.2
- A small helper can convert the name automatically and use the same call as either a getter or a setter. section 12.3.2
Listing 12.7. A simple method for accessing styles
<div style="color:red;font-size:10px;background-color:#eee;"></div>
<script>
function style(element,name,value){ #A
name = name.replace(/-([a-z])/ig, (all,letter) => { #B
return letter.toUpperCase();
});
if (typeof value !== 'undefined') { #C
element.style[name] = value;
}
return element.style[name]; #D
}
document.addEventListener("DOMContentLoaded", () => {
const div = document.querySelector("div");
assert(style(div,'color') === "red", style(div,'color'));
assert(style(div,'font-size') === "10px", style(div,'font-size'));
assert(style(div,'background-color') ===
"rgb(238, 238, 238)",style(div,'background-color'));
});
</script>
See the helper convert hyphenated names and read or set values on an element’s style property. section 12.3.2
