JavaScript element.insertAdjacentElement() Method
You are Here:
JavaScript element.insertAdjacentElement() Method
The element.insertAdjacentElement()
method inserts a the specified element into a specified position.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h2>Heading</h2>
<span style="color:blue;">Span</span>
<button onclick="myFunction()">Click Me</button>
<script>
var target = document.getElementsByTagName("h2")[0];
var elem = document.getElementsByTagName("span")[0];
function myFunction(){
target.insertAdjacentElement("beforebegin", elem);
}
</script>
</body>
</html>
Syntax
target.insertAdjacentElement(position, element)
Parameter Values
Value | Type | Explanation |
---|---|---|
position | Required | The following are the values that can be used in the place of position. 'beforebegin' - Before the target element itself. 'afterbegin' - Just inside the target element, before its first child (includes text node also). 'beforeend' -Just inside the targetElement, after its last child (includes text node also). 'afterend' - After the target element itself. |
element | Required | Specifies the element to be inserted into the tree. |
More Examples
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h2>Heading</h2>
<span style="color:blue;">Span</span>
<button onclick="myFunction()">Click Me</button>
<script>
var target = document.getElementsByTagName("h2")[0];
var elem = document.getElementsByTagName("span")[0];
function myFunction(){
target.insertAdjacentElement("afterbegin", elem);
}
</script>
</body>
</html>
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h2>Heading</h2>
<span style="color:blue;">Span</span>
<button onclick="myFunction()">Click Me</button>
<script>
var target = document.getElementsByTagName("h2")[0];
var elem = document.getElementsByTagName("span")[0];
function myFunction(){
target.insertAdjacentElement("beforeend", elem);
}
</script>
</body>
</html>
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h2>Heading</h2>
<span style="color:blue;">Span</span>
<button onclick="myFunction()">Click Me</button>
<script>
var target = document.getElementsByTagName("h2")[0];
var elem = document.getElementsByTagName("span")[0];
function myFunction(){
target.insertAdjacentElement("afterend", elem);
}
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.