Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 contexts.

like image 215
Choy Avatar asked Jan 22 '10 18:01

Choy


People also ask

How to use JavaScript in Dash?

Adding Your Own CSS and JavaScript to Dash Apps. Including custom CSS or JavaScript in your Dash apps is simple. Just create a folder named assets in the root of your app directory and include your CSS and JavaScript files in that folder. Dash will automatically serve all of the files that are included in this folder.

What do dashes mean in CSS?

This answer is not useful. Show activity on this post. -webkit- and -moz- here are called vendor prefixes; they generally indicate a browser-specific feature of CSS, or one that's under development/still a draft and can't be considered a standard yet.

Can CSS id have hyphen?

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Can JavaScript variables have hyphens?

Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in JavaScript names.


2 Answers

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.

like image 151
Parrots Avatar answered Sep 19 '22 12:09

Parrots


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!';"
like image 25
Guffa Avatar answered Sep 18 '22 12:09

Guffa