1. Home
  2. Computing & Technology
  3. JavaScript

DOM Naming Conventions

Join the Discussion

Questions? Comments?

How do you work out the Javascript name to use to reference the attributes in your HTML or stylesheet? In most cases it is just a matter of applying a couple of simple rules to convert from the HTML or stylesheet attribute name to the name that allows Javascript to access that attribute.

The rule to apply to almost all HTML attributes is simply to convert the attribute name to lowercase (if it isn't already). HTML is not case sensitive and so allows attributes to be specified in tags using either uppercase or lowercase. Javascript is case sensitive and insists on lowercase.

Example:

<IMG ID="t" SRC="myimage.gif">
document.getElementById('t').src

The same rule can be applied to almost all stylesheet attributes apart from those that contain hyphens. To convert a stylesheet attribute that contains a hypen for use with Javascript you need to capitalize the letter following the hyphen and remove the hyphen.

Example:

body {background-color:#fff;}
getElementsByTagName('body').style.backgroundColor

There are three exceptions to these rules because two HTML attributes and one stylesheet attribute have names that correspond to Javascript reserved words.

Example:

<LABEL FOR="x">

As for is a Javascript reserved word we need to use htmlFor instead.

Example:

<DIV CLASS="y">

As class is a Javascript reserved word (even though it is not actually used in version one of Javascript) we need to use className instead.

Example:

.left {float:left;}

As float is a Javascript reserved word (again not used in version one) we need to use a replacement. Unfortunately the browsers do not have a standard value to use as a replacement for this one so we need to use both styleFloat and cssFloat in order for the code to work across all browsers.

>Among its many quirks and bugs, Internet Explorer omits support for one of the most important attributes that you will need to add in your code to be able to update the web page to include form content. Internet Explorer does not allow you to add a name attribute to any of your form fields after the tag itself is created.

Explore JavaScript
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.