The nodes can be manipulated individually by any of the methods listed below.
The appendChild() method adds a nodeChild as a last child of a node. If the node is already existing, it is the first one removed.
Syntax for appendChild()
- nodeChild – Node which is being added to a parent
Example of appendChild() - how to append a heading to a paragraph node
The cloneNode() method clones a node and it’s attributes. Cloning the element copies all attributes and their values, However the parentNode of the clone node is null and it has no parent. All the descendants of the node are cloned when deep parameter is set to true. Else a shallow clone occurs.
Syntax for cloneNode()
- deep : true – Node, it’s attributes and it’s descendants are all cloned.
- deep : false – Clones only nodes and its attributes.
Example of cloneNode() - cloning a list
The insertBefore() method inserts a new child node before the existing reference child node. If the reference child is a null, new child is inserted at the end of list of children. This function can be used, for instance, to create a new list item of text, by creating Text node and append the list items, or modify an existing element.
Syntax for insertBefore()
- newChild – node to be inserted.
- refChild – reference node before which newChild is inserted.
Example of insertBefore() - inserting a list before the first one
The removeChild() method removes a specific child node from an element. If the node does not exists it returns a null, else it returns the removed node object which can be used to insert into another node. This is no longer a part of DOM.
Syntax for removeChild()
- nodeChild – node object to be removed.
Example of removeChild() - removing a list item and re-inserting into another paragraph
The replaceChild() method replaces the oldChild node with the newChild node in the list of children and returns the oldChild node. If the tree already has a newChild it is removed first.
Syntax for replaceChild()
- newChild – New node to be replace in child list.
- oldChild – Old node being replaced.
Example of replaceChild() - raplacing and old child node with the new one
The hasChildNodes() method determines whether a node has any children node. If it has childNodes it returns true, else false. Any whitespace, line feed inside a node is called a text node and is considered as child node.
Syntax for hasChildNodes()
Example of hasChildNodes() - checking if there are child nodes existing
No comments have been made yet.
Please login to leave a comment. Login now