From Text to Node

I have created a method that assists in creating your HTML elements in Javascript. textToNode takes a string of text and converts it into a DOM element which you may then use for insertion. It’s much easier to use than creating each node seperately, adding attributes to it, then appending it to the parent. It also works for table elements (tr, td, etc.) and the option element in a drop-down box.

This was created for DOMClass objects but has been very nice for creating elements on the fly. It is as easy to use as the innerHTML property of an element, but it works with table elements etc. and gives you the node reference which you may then attach code to as needed.

Javascript is beautiful.

function textToNode(text) {
	var type = text.match(/<(\w+)/)[1];
	var container = document.createElement('div');
	var elem;
	switch (type) {
		case 'thead':
		case 'tfoot':
		case 'tbody':
			container.innerHTML = '<table>' + text + '</table>';
			elem = container.firstChild.firstChild;
			break;
		case 'tr':
		case 'th':
			container.innerHTML = '<table><tbody>' + text + '</tbody></table>';
			elem = container.firstChild.firstChild.firstChild;
			break;
		case 'td':
			container.innerHTML = '<table><tbody><tr>' + text + '</tr></tbody></table>';
			elem = container.firstChild.firstChild.firstChild.firstChild;
			break;
		case 'option':
			container.innerHTML = '<select>' + text + '</select>';
			elem = container.firstChild.firstChild;
			break;
		default:
			container.innerHTML = text;
			elem = container.firstChild;
	}
	return elem;
}

First I check what type of element this is using a regular expression. Then I make a container to put my innerHTML in. Following is a switch statement to handle the special types that can’t be created using innerHTML unless inside of their native element. I assign the target node to the elem variable and then return it after the switch statement. Pretty simple, really nice to use.