Wednesday, March 1

HTML Dom uitilities ( Vanilla Javascript )

My JavaScript HTML Dom Utilities

During a new project I started I found a need for creating several DOM objects in JavaScript. Usually I would use JQuery. With this personal project I know exactly which brower I am targeting, and as such do not need a lot of the error support in JQuery.

So I have decided to write my own support routines in vanilla JavaScript, and use this as a good chance to see how much of JQuery I actually use.

You can copy the code easier from the codepen HERE.

Bare Code

Making it easy to read, I am going to have, like JQuery, my functions branch of the "$". So when I look at the code any calls starting with "$" will be my utilities.

Returning a DOM Object

One of the main needs I have is for returning a DOM object. Since I know for sure that I will be targeting very new Google Chrome builds, I do not have to worry about their being different functions to call. I will be using document.getElementById, document.getElementsByClassName, document.getElementsByTagName.

This function checks the first character of the identifer past to it in the variable "findMe". If the first character is a "#" then it returns all elements with that class name. If the first character is a "." it returns the element with that id. If neither of those characters are found then it returns all elements with that tag name.

update: thanks to afallenhope on for pointing out my mistake.

Creating a DOM Object

To simplify, well shorten, some of the typing I also want to easily be able to create DOM objects. Since I know which browser will be used this is very simple with the document.createElement function.

Programmatically setting the Style of a DOM Object

This project I wanted to set as much of the style settings for the objects as I could in the JavaScript. Instead of having multiple CSS files and worrying about what other objects I may be effecting in the future.

Originally I added this as a function of the getDomElements like I did with the create function. After thinking about it more, I liked the idea of being able to create and Object, and set the style all in one command. This made it important for me to make this a prototype feature of Object.

This is not the cleanest code. In the future I hope to get back and clean this up. It is effective though. It first tests to make sure the "style" property exists. If the "style" property does not exist it returns gracefully.

I will update this post as I add more functionality.


Post a Comment