Suppose you want to write a simple web app, one of the most common things that you will want to do is document manipulate. It is modification of the document by making some change..
Using DOM manipulation you will be able to create some interactive feature on the webpage.
Javscript provides various method by which developers can:
- Create new element
- Attach new element to the DOM
- Removing old element from the DOM
- Replacing an element with another element
- Changing the location of the element in the document
- Making change in existing element by adding style or by adding content
- Adding a new attribute to the element
DOM manipulation methods
Here is the list of the methods that we are going to use in this section:
It is common for interactive websites to create new element dynamically on user's action and use them.
So, how do you create a new element?
The way we create new elements is by using the
createElement method. Call the
createElement method via
document object and pass the tag name of the element you wish to create.
element variable return the reference of the created element.
createElement method converts the tag name of the element to lower case before creating the element.
The element created by the
createElement() method does not automatically attach to the document, we have to explicitly append elements to the document.
Since now we have created the element and also has stored the reference of the element in a variable, but the created element is floating aimlessly because DOM does not know about the created element till now.
To make the created element part of the document we have to specify it a parent element and append a newly created element to it.
To append element use the
append() method. It inserts a set of Node objects or DOMString object as a last child of the ParentNode.
The reference of Node element which has to be appended is passed as an argument to the method. The method calling element is known as the parent while the element which is appended is called the child.
Output: After button click
In an interactive web application, you will not only want to creates and append a new element to the document but also to remove any desired element.
removeChild method removes an element from the DOM structure. The Node which is to be removed is passed as an argument to the method.
removeChild returns a reference to the child node which is deleted.
- parent - Parent node whose child is to be removed
- child - Node which will be removed
Here is an example which removes the child element with id 'secondChild'.
Note: You need to call
removeChild method from the parent of the child otherwise it will throw an error.
4. Replace Element with other Element
replaceChild() method replaces a node with another node in the DOM.
- parent - Parent element whose child is to be replaced
- newElement - Element which will replace another one
- oldElement - Element which will be replaced
The method returns the element which is replaced.