JavaScript Wiki
Advertisement

The following function uses a short name and syntax to append a new element (and add any attributes) to a given Node (or series of nodes).

Definition[]

Arguments:

  1. <element name> (required)
  2. object with attributes and values
  3. DOM Node to which to append the new element (can also be given a string corresponding to the accepting node's 'id' attribute)
  4. Additional DOM Nodes (also specifiable as a string id) to which to append the previous node

Due to the word being a reserved word in JavaScript, we cannot use a "class" attribute in the attribute object (2nd argument), and instead should use "className" or "classn".

To add a text node, add "textContent" or "textc" and the text contents to the attribute object. If no DOM node is specified, you can still assign the result of the function to a variable (it will just create the element and any attributes).

Example usage[]

// Add a link to a node representing the body
var body = document.getElementsByTagName("body")[0];
adom('a', {href: "http://wikipedia.org", title: "This link leads to Wikipedia"}, body); 
// Add line break to a paragraph with id 'my_paragraph_id'
adom('br', null, 'my_paragraph_id');
// Adds a span element with a style attribute, inserts text into that element, appends the span 
// to a p, and returns the p).
var par = adom('span', {style: "color:blue;", textc: "some blue words"}, adom('p'));

JavaScript Code[]

function adom(el, atts) {
	var elem = document.createElement(el);
	for (attname in atts) {
	
		if (attname === 'textContent' || attname === 'textc') {
			var textnode = document.createTextNode(atts[attname]);
			elem.appendChild(textnode);			
		}
		else if (attname === 'className' || attname === 'classn') {
			elem.setAttribute('class', atts[attname]);
		}
		else {
			elem.setAttribute(attname, atts[attname]);
		}
	}
	if (arguments[2] == null) {
		return elem;
	}
	else {
		var nexttoappend = elem;
		for (var i=2; i < arguments.length; i++) { // >
			var argtemp = arguments[i];
			if (typeof argtemp === 'string') {
				argtemp = document.getElementById(argtemp);
			}
			argtemp.appendChild(nexttoappend);
			nexttoappend = argtemp;
		}

		return nexttoappend;
	}
}
Advertisement