119

<div id="example-value"> or <div id="example_value">?

This site and Twitter use the first style. Facebook and Vimeo - the second.

Which one do you use and why?

Deduplicator
  • 41,806
  • 6
  • 61
  • 104
Emanuil Rusev
  • 31,853
  • 50
  • 124
  • 193

8 Answers8

140

Use Hyphens to ensure isolation between your HTML and JavaScript.

Why? see below.

Hyphens are valid to use in CSS and HTML but not for JavaScript Objects.

A lot of browsers register HTML Ids as global objects on the window/document object, in big projects, this can become a real pain.

For this reason, I use names with Hyphens this way the HTML ids will never conflict with my JavaScript.

Consider the following:

message.js

message = function(containerObject){
    this.htmlObject = containerObject;
};
message.prototype.write = function(text){
    this.htmlObject.innerHTML+=text;
};

html

<body>
    <span id='message'></span>
</body>
<script>
    var objectContainer = {};
    if(typeof message == 'undefined'){
        var asyncScript = document.createElement('script');
        asyncScript.onload = function(){
            objectContainer.messageClass = new message(document.getElementById('message'));
            objectContainer.messageClass.write('loaded');
        }
        asyncScript.src = 'message.js';
        document.appendChild(asyncScript);
    }else{
        objectContainer.messageClass = new message(document.getElementById('message'));
        objectContainer.messageClass.write('loaded');
    }
</script>

If the browser registers HTML ids as global objects the above will fail because the message is not 'undefined' and it will try to create an instance of the HTML object. By making sure an HTML id has a hyphen in the name prevents conflicts like the one below:

message.js

message = function(containerObject){
    this.htmlObject = containerObject;
};
message.prototype.write = function(text){
    this.htmlObject.innerHTML+=text;
};

html

<body>
    <span id='message-text'></span>
</body>
<script>
    var objectContainer = {};
    if(typeof message == 'undefined'){
        var asyncScript = document.createElement('script');
        asyncScript.onload = function(){
            objectContainer.messageClass = new message(document.getElementById('message-text'));
            objectContainer.messageClass.write('loaded');
        }
        asyncScript.src = 'message.js';
        document.appendChild(asyncScript);
    }else{
        objectContainer.messageClass = new message(document.getElementById('message-text'));
        objectContainer.messageClass.write('loaded');
    }
</script>

Of course, you could use messageText or message_text but this doesn't solve the problem and you could run into the same issue later where you would accidentally access an HTML Object instead of a JavaScript one

One remark, you can still access the HTML objects through the (for example) window object by using window['message-text'];

bzrk
  • 105
  • 1
  • 6
Raatje
  • 1,542
  • 1
  • 10
  • 3
  • I don't understand something about your post here, perhaps you can clarify. So you say that some browsers register the html id's as global objects and that if you put a hyphen in the id then you will guarantee that there will be no conflict between these auto-generated objects and the ones that you create because hyphens are not allowed. But how then does the browser create these hyphenated objects if hyphens are not allowed? seems like it would have to strip them, thus leaving you with the potential of a naming conflict. – Dallas Caley Mar 28 '16 at 20:43
  • @DallasCaley if you didn't see, this answer was update calling out `window['message-text'];` – Chris Marisic Jun 02 '16 at 19:38
  • Ah i think i get it. Strange that javascript doesn't allow you to create an object with a dash in the name as a stand-alone object, but it will allow you to create an object with a dash in the name if it is created as a property of another object that doesn't have a dash in the name. – Dallas Caley Jun 03 '16 at 15:20
  • This post actually caused me to rethink my position into almost 100% agreement with you from a position of no that is silly, my only reservation is given your position on the issue it seems evident that every id should have a - in it to prevent the same issue unless you specifically want it to work for some particular ids. – user254694 May 18 '18 at 11:05
93

I would recommend the Google HTML/CSS Style Guide

It specifically states:

Separate words in ID and class names by a hyphen. Do not concatenate words and abbreviations in selectors by any characters (including none at all) other than hyphens, in order to improve understanding and scannability.

/* Not recommended: does not separate the words “demo” and “image” */
.demoimage {}

/* Not recommended: uses underscore instead of hyphen */
.error_status {}

/* Recommended */
#video-id {}
.ads-sample {}
Spencer O'Reilly
  • 355
  • 1
  • 4
  • 17
Klas Mellbourn
  • 35,589
  • 18
  • 119
  • 143
  • 1
    What about [`BEM`](http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax) notation? – Iulian Onofrei Jul 30 '14 at 07:18
  • 1
    @IulianOnofrei you are of course free to use BEM, but it clearly does not adhere strictly to the Google Style Guide. – Klas Mellbourn Sep 01 '15 at 17:18
  • hmm, very weird. The GWT framework from google uses camelcase. Check this line of code

    in the following docu. http://www.gwtproject.org/doc/latest/tutorial/i18n.html
    – karlihnos Feb 22 '17 at 13:38
  • 4
    Google != automatically right. They often are, but just being Google isn't enough of a justification. – Craig Brett Sep 01 '17 at 09:11
  • 2
    This is a really bad idea. Sooner or later you will want to use your name in a programming language that doesn't support hyphens in variable names (basically all of them), and then BOOM! [Idiotic renaming rules.](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style) – Timmmm Nov 18 '19 at 16:15
5

It really comes down to preference, but what will sway you in a particular direction might be the editor you code with. For instance, the auto-complete feature of TextMate stops at a hyphen, but sees words separated by an underscore as a single word. So class names and ids with the_post work better than the-post when using its auto-complete feature (Esc).

Doug Neiner
  • 62,310
  • 11
  • 103
  • 117
4

I believe this is entirely up to the programmer. You could use camelCase too if you wanted (but I think that would look awkward.)

I personally prefer the hyphen, because it is quicker to type on my keyboard. So I would say that you should go with what you are most comfortable with, since both your examples are widely used.

adamse
  • 11,732
  • 4
  • 32
  • 46
  • 3
    this question is similar and verifies this answer http://stackoverflow.com/questions/70579/what-is-a-valid-value-for-id-attributes-in-html – Matt Smith Nov 08 '09 at 15:48
2

Either example is perfectly valid, you can even throw into the mix ":" or "." as separators according to the w3c spec. I personally use "_" if it is a two word name just because of its similarity to space.

Myles
  • 18,830
  • 3
  • 24
  • 35
0

I use the first one (one-two) because its more readable. For images though I prefer the underscore (btn_more.png). Camel Case (oneTwo) is another option.

eozzy
  • 58,300
  • 96
  • 249
  • 396
0

Actually some external frameworks (javascript, php) have difficulties (bugs?) with using the hypen in id names. I use underscore (so does 960grid) and all works great.

DavidHavl
  • 347
  • 3
  • 10
-1

I would suggest underscore mainly for the reason of a javascript side-effect I'm encountering.

If you were to type the code below into your location bar, you would get an error: 'example-value' is undefined. If the div were named with underscores, it would work.

javascript:alert(example-value.currentStyle.hasLayout);
jgreep
  • 1,971
  • 4
  • 21
  • 28
  • 5
    That should be `document.getElementById("example-value")`, which will work fine. – Chuck Jan 07 '10 at 16:41
  • I am getting a similar problem with ASP.NET MVC when specifying a value for an attribute in the HtmlAttributes parameter of Html helper functions. – Matthijs Wessels Feb 28 '11 at 07:52