insertAdjacentElement() method in javascript
insertAdjacentElement() method is used to insert new HTML element at a specific position.
Position can be represented using following values,
- 'beforebegin' : Insert the HTML element before the specified element.
- 'afterbegin' : Insert the HTML element inside the specified element, but before its first child.
- 'beforeend' : Insert the HTML element inside the specified element, but after its last child.
- 'afterend' : Insert the HTML element after the specified element.
Example Explanation
- In the above example we have added a paragraph and created two buttons and two Javascript functions are declared for those buttons (fun_before(), fun_after()).
- When the button is clicked Javascript function is called.
- If the first button is clicked, fun_before() is called. In here it adds the element just above the paragraph.
- If the second button is clicked, fun_after() is called. In here it adds the element just after the paragraph.