DOM Node relative

Identifying the Type and Name of a Node

Every node has a nodeType and nodeName property that is inherited from Node.

Node.nodeName Node.nodeType

Getting a Node’s Value

The nodeValue property returns null for most of the node types (except Text and Comment). Its use is main on extracting actual text strings from Text and Comment nodes.


Using JavaScript Methods to Create Element and Text Nodes

create Element and Text nodes using JavaScript

  • createElement()
  • createTextNode()

Other methods are available but are not commonly used (e.g., createAttribute() and createComment()).

var elementNode = document.createElement('div');  

var textNode = document.createTextNode('Hi');  

The createElement() method accepts one parameter that is a string specifying the element to be created. The string is the same string that is returned from the tagName property of an Element object.

Using JavaScript Strings to Create and Add Element and Text Nodes to the DOM

The innerHTML, outerHTML, textContent, and insertAdjacentHTML() properties and methods provide the functionality to create and add nodes to the DOM using JavaScript strings.

<div id="A">A</div>  
<span id="B">B</span>  
<div id="C">C</div>  
<div id="D">D</div>  
<div id="E">E</div>

document.getElementById('A').innerHTML = '<strong>Hi</strong>';  
document.getElementById('B').outerHTML =  
document.getElementById('C').textContent =  
document.getElementById('D').innerText = 'Keep it';  
document.getElementById('E').outerText = 'real!';  

The outerText create a text node and replace the origin node with the text node.

The innerText create a text node and update the origin node with the text node

The innerHTML create a element node and add it to the DOM.

The outerHTML create a element node and replace the origin node with the text node.

The insertAdjacentHTML() method, which only works on Element nodes. It can insert nodes before the beginning tag, after the beginning tag, before the end tag, and after the end tag.

The innerHTML property will convert HTML elements found in the string to actual DOM nodes.

textContent can only be used to construct text nodes. If you pass textContent a string containing HTML elements, it will simply spit it out as text.

The insertAdjacentHTML options beforebegin and afterend will only work if the node is in the DOM tree and has a parent element.

textContent gets the content of all elements, including <script> and <style> elements, but innerText does not. innerText is aware of style and will not return the text of hidden elements, whereas textContent will.

The textContent, innerText, and outerText properties, when being read, will return all the text nodes contained within the selected node