Javascript parentNode and childNode

  1. append multiple children to a parentNode at once

The ParentNode.append() method inserts a set of Node objects or DOMString objects after the last child of the ParentNode. DOMString objects are inserted as equivalent Text nodes.

Differences from Node.appendChild():

  • ParentNode.append() allows you to also append DOMString objects, whereas Node.appendChild() only accepts Node objects.
  • ParentNode.append() has no return value, whereas Node.appendChild() returns the appended Node object.
  • ParentNode.append() can append several nodes and strings, whereas Node.appendChild() can only append one node.

e.g.

main.appendChild(div)

2. count number of children

The ParentNode.childElementCount read-only property returns an unsigned long representing the number of child elements of the given element.

I used this when count number of li in an ul.

3.prepend: insert before the first child

The ParentNode.prepend() method inserts a set of Node objects or DOMString objects before the first child of the ParentNode. DOMString objects are inserted as equivalent Text nodes.

This comes handy when append some text in front of other children nodes.

4. access previous or next sibling

node.previousSibling

5. delete parentNode

node.parentNode.remove()

this will remove the whole parent node including all the childNodes in it.

Sources: