Javascript and CSS, using dashes

I'm starting to learn some javascript and understand that dashes are not permitted when naming identifiers. However, in CSS it's common to use a dash for IDs and classes.

Does using a dash in CSS interfere with javascript interaction somehow? For instance if I were to use getElementByID("css-dash-name"). I've tried a few examples using getElementByID with dashes as a name for a div ID and it worked, but I'm not sure if that's the case in all other context.


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.


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!';"

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.

链接地址: http://www.djcxy.com/p/88308.html

上一篇: 来自“数据”的案例映射

下一篇: Javascript和CSS,使用破折号