Naming variables that store DOM elements

There are several common naming conventions for variables that refer to DOM elements. This article describes how they work and what they aim to do.

What are the goals when naming a DOM element variable?

The first goal is to make it clear that it's a DOM element. You want to know if dialog refers to the dialog class or the DOM element that contains the dialog content.

Secondly, you want to know whether the element is a plain DOM Element, or a jQuery/Angular element object.

Naming with a dollar prefix

This is a common naming convention when working with jQuery. You might have code like this:

var $dialog = $("#dialog");
var dialog = new Dialog($dialog);

In the code above we have two dialog variables, but only the one prefixed with a dollar sign represents a DOM element.

The dollar prefix can also differentiate between native DOM Elements and jQuery objects. Here's an example:

$("h3").each(function(i, heading){
    var $heading = $(heading);
    console.log($heading.text())
})

The heading variable holds a native DOM object, which doesn't have the .text function. $heading however is a jQuery element object, meaning you have all jQuery functions available on it.

Using this prefix exclusively for jQuery element objects can give certainty about what the variable can be used for, or whether it first needs to be converted.

Naming with element type postfixes

This approach works by including the type of an element in its variable name. For example, the dialog element might be called dialogDiv, or just dialogElement.

In this approach, there is no differentiation between native DOM Elements and jQuery element objects. However, this problem can be avoided by making sure that all elements are always jQuery objects.

$("h3").each(function(i, headingElement){
    headingElement = $(headingElement);
    console.log(headingElement.text())
})

If an element is a native DOM Element then it should always be converted to a jQuery element object. That way you can have consistent expectations towards an element's functionality, meaning the methods that are available on it.

So, what's the best approach?

Naming element variables is ultimately down to preference. As long as you keep in mind the two goals mentioned at the top of this post you'll be doing better than most projects.

On a final note, avoid meaningless names like el, unless they refer to the container element of a view.

Get an email with a new articles once a week.