DEV Community

EDDYMENS
EDDYMENS

Posted on • Edited on

Be careful with HTML ID attributes

What are HTML attributes?

Sample HTML element

HTML is made up of elements which help define the structure of a web page, Elements of the same type possess the same behavior across a web page. One way to make an element behave differently is by adding properties to them. One of the ways to add a property to an HTML element is using the attributes, for example, you can add CSS styles to elements using selector attributes like classes, ids, and names.

Working with selectors

class and name attributes

Selectors help you target specific HTML elements, this way you can easily attach CSS styles or behaviors using Javascript. The most commonly used attributes are classes, ids, and names. Although any of these selectors can be used to add either style or behaviors.

Usually, classes are used to add styles to elements simply because an element can have multiple classes and multiple elements can have the same classes, meaning you can apply multiple styles to an element as well as apply one style to different elements. Names are usually used with input elements to not only mark as the key for the data they collect and send to the server but also sometimes for applying targeted styles. More than one input can share a name, the reason being that you may have more than one form within a page.

The ID attribute

Accessing input values using Id variables

Ids, unlike classes and names, should be assigned to only one element, its meant to serve as a unique identifier for accessing elements. But based on the specification most browsers convert ids into variables meaning you have access to the DOM of that particular element.

Not using ids carefully could lead to polluting the javascript global scope, this might also lead to problems if your ids collide with the variable names within the global scope.

Also at first glance, this might be seen as an easier way to access the DOM of any element with just the id name without having to use query selectors. But this is a bad idea as a browser like Firefox discourages the use of this. It's much safer to just go with query selectors.

A simple solution

Using invalid variable names as Ids

Unfortunately, the conversion of ids into variables is something that is out of your control, but you can gain back that control, one way is to use invalid variable names as id names, this way there is no way it will conflict with your variables in the global scope. But sometimes you can’t due to a naming conversation or some other reason, in which case the best option is to try to use fewer ids where and when possible.

Top comments (0)