My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Monday, February 09, 2009

JavaScript, Bear in Mind DOM Methods

We all like the jQuery code style where the instance is returned almost everywhere, but we often forget about DOM methods that do the same and ages before whatever library. I rarely spot some "returned instance" trick in daily posts or even famous libraries.
Here a couple of example:

// daily way ...
var div = document.createElement("div");

// easy way
var div = document.body.appendChild(document.createElement("div"));

// boring way
var div = document.createElement("div");

// funny way
var div = document.body.appendChild(

... on and on, there are several methods used on daily basis that do not consider returned values. So, why don't we like to use them?

var el = document.createElement("div"),
div = document.createElement("div");
el === document.documentElement.appendChild(el), // el in the DOM
el === el.parentNode.removeChild(el), // el removed
div === document.documentElement.appendChild(div), // div in the DOM
div === div.parentNode.replaceChild(el, div), // div removed, el in the DOM
div === el.parentNode.insertBefore(div, el) // both in the DOM, div returned

As summary, try to find a leak possibility with this:

with((document.body || document.documentElement)
)) parentNode
document.createTextNode("Why "),
document.createTextNode(" ?")

Not even a single variable declared, three elements inserted in a specific node of the DOM and in a different order :D

No comments: