HelmJS
Lately I have been trying to encapsulate some functions that I use in my day to day development.
Today I will introduce HelmJS, a Curry based DOM Factory for vanilla Javascript and jQuery.
Maybe the name is even more complicated that what it does. Basically I made a wrapper that follows this rule:
$('<div>') === $div()
$('<div>') is the fastest way to create an HTML element in jQuery.
You then can chain some other functions as follow:
$('<div>').attr( "class":"fitter happier" ).text( "more productive" ).appendTo( $container );
It will create a DIV element, with two classes: fitter happier, with the text "more productive" and append it to an already declared $container. Also you can bind events like on click, etc. ( That jQuery object is awesome! )
So far this seems really convenient. BUT, reading the jQuery source I found out that any string passed to $() is evaluated as if it is an HTML string representation ( $('<div>') ) or a Sizzle Selector ( $('div.some-class') ).
So, I don't know if this is completely ok, it works I know, but what happens when you write $('div') ( notice the lack of <> ) with that expression you are selecting ALL DIVs in your DOM and not creating any. Kind of an easy bug right there huh?
I have created some Perfs to test which is the fastest way to create HTML elements using jQuery.
Then I asked my self, what if we use the native javascript way to create HTML elements, which is document.createElement() and wrap it up with a $() Object, this way jQuery won't need to test if it is a selector or not :
$( document.createElement('div') );
Its Perf Test shows a better performance for this more native solution.
Next, I found that with the use of curries we can specify custom functions for each HTML Element available. ( How to set up curry functions )
Ending up with these custom functions:
div() or a() as encapsulated forms of $(document.createElement('div')) or $(document.createElement('a'))
But since these Curries need to live in a very global scope I decided to use the *hungarian notation(?)* of $ to specify that they return jQuery objects and also to prevent problems with variables named a or the famous i etc.
And that is how HelmJS was born.
I've curried all the HTML elements in this MDN list. This also prevents you to select all DIVs by mistake as explained earlier since you only have one way to create a DIV.
There is also included a Vanilla Version that works with document.createDocumentFragment(). See the example in the github repo.
I don't necessary recommend to use HelmJS in a production or a very serious project, it needs more testing. Also it is most likely that you will be using some MVC Framework or Template Engine to build your HTML elements. But if you are planning to do so at least you were informed ( and please let me know ).
HelmJS should be one more tool in your utility belt but not your definitely solution, less keyboard strokes are always good right?














