Javascript and CSS, using dashes

Using Hypen (or dash) is OK

I too is currently studying JavaScript, and as far as I read David Flanagan's book (JavaScript: The Definitive Guide, 5th Edition) — I suggest you read it. It doesn't warn me anything about the use of hypen or dash (-) in IDs and Classes (even the Name attribute) in an HTML document.

Just as what Parrots already said, hypens are not allowed in variables, because the JavaScript interpreter will treat it as a minus and/or a negative sign; but to use it on strings, is pretty much ok.

Like what Parrots and Guffa said, you can use the following ...

  1. [ ] (square brackets)
  2. '' (single quotation marks or single quotes)
  3. "" (double quotation marks or double quotes)

    to tell the JavaScript interpreter that your are declaring strings (the id/class/name of your elements for instance).


Use Hyphen (or dash) — for 'Consistency'

@KP, that would be ok if he is using HTML 4.1 or earlier, but if he is using any versions of XHTML (.e.g., XHTML 1.0), then that cannot be possible, because XHTML syntax prohibits uppercase (except the !DOCTYPE, which is the only thing that needs to declared in uppercase).

@Choy, if you're using HTML 4.1 or earlier, going to either camelCase or PascalCase will not be a problem. Although, for consistency's sake as to how CSS use separators (it uses hypen or dash), I suggest following its rule. It will be much more convinient for you to code your HTML and CSS alike. And moreoever, you don't even have to worry if you're using XHTML or HTML.


Whenever you have to address a CSS property as a JavaScript variable name, CamelCase is the official way to go.

element.style.backgroundColor = "#FFFFFF";

You will never be in the situation to have to address a element's ID as a variable name. It will always be in a string, so

document.getElementById("my-id");

will always work.


It's only in the cases where you can access the elements as properties that it makes a difference. For example form fields:

<form>
   <input type="text" name="go-figure" />
   <input type="button" value="Eat me!" onclick="...">
</form>

In the onclick event you can't access the text box as a property, as the dash is interpreted as minus in Javascript:

onclick="this.form.go-figure.value='Ouch!';"

But you can still access it using a string:

onclick="this.form['go-figure'].value='Ouch!';"

Having dashes and underscores in the ID (or class name if you select by that) that won't have any negative effect, it's safe to use them. You just can't do something like:

var some-element = document.getElementByID('css-dash-name');

The above example is going to error out because there is a dash in the variable you're assigning the element to.

The following would be fine though since the variable doesn't contain a dash:

var someElement = document.getElementByID('css-dash-name');

That naming limitation only exists for the javascript variables themselves.