Don’t initialise Javascript automagically

I used to write Javascript that initialises components automagically, like this:

var datepickers = document.getElementsByClassName(‘datepicker’); for(var i = 0; i < datepickers.length; i++) { new DatePicker(datepickers[i]); }

It works by looping over every element with a particular class name. For each element found a date picker is created automagically.

Developers like this because it’s just 4 lines of code. And it never needs updating—theoreticaly at least. If you want another date picker, just add a class of date picker and done.

Except it’s not as simple as that. This approach has many downsides which I’ll explain here.

# 1.

See original post