The following code shows an Example of insertAdjacentText() Method in JavaScript.
Programmingempire
Illustrating an Example of insertAdjacentText() Method in JavaScript
Like insertAdjacentHTML() method, this method also inserts the given text at a specific position. However, this method adds a text rather than an HTML element.
<html>
<head>
<title>insertAdjacentText Method Demo</title>
<script>
function f1()
{
var v1=document.getElementById("d1");
v1.insertAdjacentText('beforebegin','Sample Text 1');
}
function f2()
{
var v1=document.getElementById("d1");
v1.insertAdjacentText('afterbegin','Sample Text 2');
}
function f3()
{
var v1=document.getElementById("d1");
v1.insertAdjacentText('beforeend','Sample Text 3');
}
function f4()
{
var v1=document.getElementById("d1");
v1.insertAdjacentText('afterend','Sample Text 4');
}
</script>
<style>
.c1{
border: 4px solid #33ff99;
border-radius: 10px;
background-color: #5566aa;
color: #aaffff;
font-size: 20px;
text-align: center;
margin:5px;
padding: 10px;
}
.a1{
margin: 50px;
}
.c2{
background-color: #ddeeff;
color: #ff5566;
font-size: 25px;
text-align: left;
margin:40px;
padding: 5px;
width: 800px;
}
</style>
</head>
<body>
<div id="d1" class="c2"><br/><br/>
Example of insertAdjacentText() Method<br/>
<br/><br/>
<button id="b1" class="c1" onclick="f1()">Add Text Before Begin</button>
<button id="b2" class="c1" onclick="f2()">Add Text After Begin</button>
<button id="b3" class="c1" onclick="f3()">Add Text Before End</button>
<button id="b4" class="c1" onclick="f4()">Add Text After End</button>
</div>
</body>
</html>
Output
Further Reading
Evolution of JavaScript from ES1 to ES2020
Introduction to HTML DOM Methods in JavaScript