EDDYMENS

Last updated 2020-01-14 13:57:14

Be Careful With HTML ID Attributes

Table of contents

Sample HTML element [→]

What are HTML attributes?

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, classes are prefered when it comes to adding styles to elements. This is because an element can have multiple classes and different elements can use these classes.

This means you can apply multiple styles to an element as well as apply one style to multiple elements.

The name attribute is used with input elements to both mark as the key for the data they collect. Additionally, it can be used to apply 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. The variable will contain the DOM object of the 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.

This is a bad idea. 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.

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.

Here is another article you might like 😊 "Diary Of Insights: A Documentation Of My Discoveries"