Adding New Elements to DOM
You can create new element in an HTML document, using the document.createElement() method. This method creates a new element, but it doesn’t add it to the DOM.
To add the new element at the end of any other children of a specified parent node use the appendChild() method.
However, if you want to add the new element at the beginning of any other children you can use the insertBefore() method.
To create a text string use createTextNode() .
Example :
Getting or Setting HTML Contents to DOM
You can also get or set the contents of the HTML elements easily with the innerHTML property. This property sets or gets the HTML markup contained within the element i.e. content between its opening and closing tags.
Example :
But there is one problem, the innerHTML property replaces all existing content of an element. So if you want to insert the HTML into the document without replacing the existing contents of an element, you can use the insertAdjacentHTML() method.
This method accepts two parameters: the position in which to insert and the HTML text to insert. The position must be one of the following values: "beforebegin" , "afterbegin" , "beforeend" , and "afterend"
Example :
The innerText property sets or returns the text content of the specified node.
If you set the innerText property, any child nodes are removed and replaced by a single Text node containing the specified string.
The textContent property is same as innerText property, but the difference is textContent property returns text with spaces where as innerText returns text with out spaces.
Example :
Removing Existing Elements from DOM
We can use the removeChild() method to remove a child node from the DOM.
Example
Replacing Existing Elements in DOM
We can also replace an element in HTML DOM with another using the replaceChild() method. This method accepts two parameters: the node to insert and the node to be replaced. It has the syntax like parentNode.replaceChild(newChild, oldChild) .
Example :