DOM manipulation is a process or a way by which you can change the structure of DOM by including new elements, deleting older elements, making changes in existing elements etc.
DOM manipulation includes :
- Create new element
- Attach new element to the DOM
- Removing old element from the DOM
- Replacing an element with another element
- Making change in existing element by adding style or by adding content
- Adding new attribute to the HTML element
There are lots of things that we can do in DOM manipulation, but before manipulating DOM we need to select the element that we want to change.
To select the element use DOM access methods. One of the most used element selection methods is
Now as we have selected the DOM element so we can use the DOM manipulation method on the element.
DOM manipulation methods
In this section we will look at those DOM methods which change the structure of DOM. Lets first list the methods and then see their examples and explanations.
1. createElement() - Create an HTML element
createElement() method creates HTML elements using the tag name of the elements like 'p', 'a', 'h1', 'div' etc.
The tag name of the element is passed as arguments in the method. Example
document.createElement('p') will create a 'p' tag.
createElement()method does not automatically attach to the document, we have to explicitly append elements to the document.
2. appendChild() - Append an HTML element to the parent element
appendChild() method appends an element as the last child of the element which invokes this method.
The element which has to be appended is passed as an argument to the method. The method calling element is known as parent while the element which is appended is called child.
3. removeChild() - Remove an Element from the DOM
removeChild() method removes an element from the DOM structure. The element which is to be deleted is passed as an argument to the method.
removeChild() also returns reference to the child node which is deleted.
- parent - Parent element whose child to be removed
- child - Element which will be removed
4. replaceChild() - Replace an Element with other Element
replaceChild() method replaces one element with another element in the DOM.
- parent - Parent element whose child to be replaced
- newElement - Element which will replace other one
- oldElement - Element which will be replaced