liveBook · Manning

Camel case

As explained in Secrets of the JavaScript Ninja, Second Edition

A naming convention in which words are joined without spaces and each word after the first begins with a capital letter.

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

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains hyphen conversion and demonstrates a getter-setter helper, while deferring computed styles.
Examples
Uses font-size and background-color as examples, alongside a helper that reads and sets style values.
What it assumes
Assumes familiarity with CSS style names and JavaScript property access; does not establish either from zero.
What you can do after
Apply camel-case conversion to access or set CSS styles through an element’s style property.
How it connects
Connects CSS property names with JavaScript property access, DOM element styles, and regular expressions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.