Javascript parentNode and childNode

Cindy Zheng
2 min readApr 27, 2020

--

  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)// div.appendChild(pTrainer)// div.appendChild(addPokemonBtn)// div.appendChild(ul)div.append(pTrainer, addPokemonBtn, ul)

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.previousSiblingpreviousSibling returns the previous sibling node as an element node, a text node or a comment nodenode.previousElementSiblingpreviousElementSibling returns the previous sibling node as an element node (ignores text and comment nodes).Same for next sibling:
node.nextSibling

node.nextElementSibling

5. delete parentNode

node.parentNode.remove()

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

Sources:

--

--

No responses yet