Elementals.js

Latest Version: 2.0 RC 3 14 March 2017

Method _.nodeAdd

Summary:

Adds either a string or a DOM Element to the target element or before/after it.

Calling Convention:
_.nodeAdd(Element, content[, place])
Parameters:
Element
The target Element to which the content is added to or placed around.
content
If content is an object, it will be added directly. If not, it will be run through document.createTextNode before being added.
place optional

Where the element will be placed. If place is omitted or invalid, 'last' is the default.

  • 'after' -- content will be placed after the Element as a sibling
  • 'before' -- content will be placed before the value as a sibling
  • 'first' -- content will be placed before the Element.firstChild
  • 'last' -- content will be placed after Element.lastChild
  • 'replace' -- content will replace the passed Element
Returns:
Nothing

Example #1

HTML

<h1>Test</h1>

JavaScript

var
	h1 = document.getElementsByTagName('h1')[0],
	h2 = document.createElement('h2');
_.nodeAdd(h1, "\r\nAdded after the H1\r\n", 'after');
_.nodeAdd(h1, "Added before the H1\r\n", 'before');
_.nodeAdd(h1, "\r\nAdded before H1 content\r\n", 'first');
_.nodeAdd(h1, h2, 'after');
_.nodeAdd(h1, "\r\nAdded after H1 content\r\n", 'last');
_.nodeAdd(h2, 'Second Heading');

RESULT HTML (equivalent)

Added before the h1
<h1>
Added before H1 content
Test
Added after H1 content
</h1>
Added after the H1
<h2>Second Heading</h2>

In practice much of the above would actually be coded using _.make. In fact, _.make's content attribute calls this method.