Elementals.js

Latest Version: 2.0 RC 3 14 March 2017

Method _.make

Summary:

Creates an element from a CSS style selector, with any desired attributes and placed on the DOM as desired. This is done using DOM creation instead of innerHTML so as to bypass the parser resulting in faster changes and none of the headaches innerHTML can introduce.

Calling Convention:
_.make(selector, attributes)
Parameters:
selector
A CSS style selector to be parsed to create the element. Note, sibling/child selectors are invalid and the selector should follow the order tagName#id.class.class.class. If tagName is not specified a <div> will be created. The ID and classes are optional.
attributes

An object of attributes that also includes a handful of special commands that can be used to place the element on the DOM as well as to specify the contents.

The Elementals "command attributes" for make are:

  • after -- The new Element will be placed after the value as a sibling
  • before -- The new Element will be placed before the value as a sibling
  • content -- This value will be inserted inside the new Element
  • first -- The new Element will be placed before the Element.firstChild of the value
  • last -- The new Element will be placed after the Element.lastChild of the value
  • replace -- The new Element will replace the Element stated as the value.

For more information on after, before, first, last, and replace see _.nodeAdd.

Any onevent attributes you passed will be parsed so as to be handled by _.eventAdd so that they will function identically across all browsers with the Event object being passed as a parameter to the callback, and Event.target and Event.currentTarget correctly resolving as expected -- even in legacy versions of Internet Explorer that use JScript instead of actual JavaScript / ECMAScript.

Returns:
The newly created Element.

Example #1

JavaScript

_.make('div#test', {
	content : 'This is a test',
	last : document.body
});

Is roughly equivalent to:

JavaScript

document.body.innerHTML += '<div id="test">This is a test</div>';

Except that it uses the DOM to do it, bypassing the parsing engine.

Example #2

JavaScript

_.make('h2.scriptHeading', {
	content : 'Test',
	after : document.getElementsByTagName('h1')[0];
});

Inserts after the first h1 on the page the equivalent of <h2 class="scriptHeading">Test</h2>, using the DOM instead of browser parsing.