Namespace: Elements:createNode

Elements:createNode

Source:

Methods

createNode(tagopt, nullable, attributesopt, nullable, contentopt, nullable) → {HTMLElement}

Creates an element on the fly programmatically, based on provided name, attributes and content or markup, without inserting it into the DOM.

If you provide markup as "tag", make sure that there is one single root element, this method returns exactly one element, not a NodeList. Also be sure to not just pass HTML source from an unsecure source, since this method does not deal with potential security risks.

One thing about dynamically creating script tags with this: if you want the script is javascript and you want to actually execute the script upon adding it to the dom, you cannot provide the complete tag as a source string, since scripts created with innerHTML will not execute. (see: https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations) Instead, just provide the tag name and define attributes and source via the parameters instead.

Parameters:
Name Type Attributes Default Description
tag String <optional>
<nullable>
'span'

tag of the element to create or markup for root element

attributes Object <optional>
<nullable>
null

tag attributes as key/value-pairs, will also be added to provided markup

content String <optional>
<nullable>
null

content to insert into the element as textContent, be aware, that this will replace other content in provided markup

Source:
Returns:
the created DOM-node
Type
HTMLElement
Example
document.body.appendChild(
  createNode('div', {id : 'content', style : 'display:none;'}, 'loading...')
);
document.body.appendChild(
  createNode('<div id="content" style="display:none;">loading...</div>')
);
document.body.appendChild(
  createNode('script', {type : 'text/javascript'}, 'alert("Hello World");');
);