Saturday, September 22, 2007

[COW] document.create cross-browser implementation

This COW goal is to use a simple, cross-browser and fast way to create a DOM element.


About document.createElement


This function works in a different way if used inside browser Internet Explorer.
This allows developers to create some HTML element instead of single one using its tag name.

// Only with IE
document.body.appendChild(
document.createElement("<iframe />")
);

Some library uses personal function to add an element, using its tag name, or to add a piece of HTML code, using innerHTML property instead of DOM element creation and manipulation.


About document.createTextNode


This function works in the same way inside every browser and its goal is to create a text node to add inside another element.

document.body.appendChild(
document.createTextNode("Hello Text Element")
);

A Text Element is the correct way to write something inside a generic HTMLElement and doesn't work as innerHTML because it automatically escape each char.



About COW, document.create function


This function choose what kind of element You need to create automatically.
Its behaviour is based on sent argument string:

  • document.create("div"), creates an HTMLElement (in this case a div) using DOM and document.createElement function

  • document.create("<span>Hello</span>"), creates a span element with "Hello" text using innerHTML to create entire element

  • document.create("#This is a text element"), creates an element using document.createTextNode and return them



document.create just analyze first argument string char.
If this is "<", You're creating an element and its content using innerHTML without modify current DOM while if first char is this one "#" You're creating a TextNode.
In other cases You're creating a generic element using regular document.createElement function.

In this last case You can use more than one argument to append nested elements.

Do You need an example ?

onload = function(){

for(var key in {
"<h2>This is a document.create example</h2>":1,
"hr":2,
"#And this is just a comment":3
})
document.body.appendChild(document.create(key));

document.body.appendChild(
document.create("div", "#And this is just a list", "<ul><li>item 1</li><li>item 2</li></ul>")
);

};


You can view this example at work here while updated function code is in this one.

Do You like them?

P.S. Robert, I think this function should be a cool DOMAssistant add on, do You agree?

No comments:

Post a Comment