JavaScript element.insertAdjacentHTML() Method
You are Here:
JavaScript element.insertAdjacentHTML() Method
The element.insertAdjacentHTML()
method inserts a the specified html into a specified position.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h2>Heading</h2>
<button onclick="myFunction()">Click Me</button>
<script>
var target = document.getElementsByTagName("h2")[0];
var text = '<span style="color:blue;">Span</span>';
function myFunction(){
target.insertAdjacentHTML("beforebegin", text);
}
</script>
</body>
</html>
Syntax
element.insertAdjacentHTML(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. |
text | Required | Specifies the string to be parsed as HTML or XML and inserted into the tree. |
More Examples
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h2>Heading</h2>
<button onclick="myFunction()">Click Me</button>
<script>
var target = document.getElementsByTagName("h2")[0];
var text = '<span style="color:blue;">Span</span>';
function myFunction(){
target.insertAdjacentHTML("afterbegin", text);
}
</script>
</body>
</html>
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h2>Heading</h2>
<button onclick="myFunction()">Click Me</button>
<script>
var target = document.getElementsByTagName("h2")[0];
var text = '<span style="color:blue;">Span</span>';
function myFunction(){
target.insertAdjacentHTML("beforeend", text);
}
</script>
</body>
</html>
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<h2>Heading</h2>
<button onclick="myFunction()">Click Me</button>
<script>
var target = document.getElementsByTagName("h2")[0];
var text = '<span style="color:blue;">Span</span>';
function myFunction(){
target.insertAdjacentHTML("afterend", text);
}
</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.