Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
HTML DOM insertAdjacentHTML( ) Method
The HTML DOM insertAdjacentHTML() method inserts text string as HTML at a specified position.
Syntax
Following is the syntax −
Calling insertAdjacentHTML() with parameters of positionString and HTML code
node.insertAdjacentHTML(“positionString”, “htmlString”)
Position Strings
Here, “positionString” can be the following −
| positionString | Description |
|---|---|
| afterbegin | It inserts htmlString after the beginning of node element |
| afterend | It inserts htmlString after the node element |
| beforebegin | It inserts htmlString before the node element |
| beforeend | It inserts htmlString before the end of node element |
Html Strings
and, “htmlString” can be the following −
| positionString |
<span>new span</span> or <p>This is a new paragraph</p> or any other valid html code |
Example
Let us see an example for InsertAdjacentHTML() method −
<!DOCTYPE html>
<html>
<head>
<title>insertAdjacentHTML()</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
}
input[type="button"] {
border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>insertAdjacentHTML( )</legend>
<h1>Family Tree</h1>
<span id="GrandFather">Grand Father --></span>
<span id="Father">Father --></span>
<span id="Myself">Myself</span>
<input type="button" onclick="rectifyTree()" value="Son is born">
</fieldset>
</form>
<script>
function rectifyTree() {
var MSpan = document.getElementById("Myself");
MSpan.insertAdjacentHTML("afterend", "<span id='Son'>-->Son</span>");
}
</script>
</body>
</html>
Output
This will produce the following output −
Before clicking ‘Son is born’ button −

After clicking ‘Son is born’ button −

Advertisements