Manipulating Element Text Content and Dynamically Adding or Removing DOM Nodes
The innerHTML property allows reading or writting the HTML content inside an element, including any nested tags. In contrast, innerText deals only with the visible text content, ignoring HTML markup. For form controls like <input>, the value property is used to get or set their current valuee.
<html>
<head>
<meta charset="UTF-8">
<title>Text Content Manipulation</title>
<style>
div {
border: 1px solid red;
width: 200px;
height: 200px;
}
</style>
<script>
function readContent() {
const container = document.getElementById("d1");
console.log("innerText >>>", container.innerText);
console.log("innerHTML >>>", container.innerHTML);
const inputField = document.getElementById("i1");
console.log("Input value >>>", inputField.value);
}
function updateContent() {
const container = document.getElementById("d1");
container.innerHTML = "<h1>Never to be divided</h1>";
const inputField = document.getElementById("i1");
inputField.value = "Wherever I go";
}
</script>
</head>
<body>
<div id="d1">
a
<span>text</span>
b
</div>
<input type="text" value="My Country and I" id="i1" />
<input type="button" value="Read Content" onclick="readContent()" />
<input type="button" value="Update Content" onclick="updateContent()" />
</body>
</html>
New elements can be created dynamically using document.createElement(). Once created, they can be inserted into the DOM with appendChild(). To remove an element, use removeChild() on its parent node.
<html>
<head>
<meta charset="utf-8">
<title>Dynamic Node Management</title>
<style>
#d1 {
border: 1px solid red;
width: 80%;
height: 200px;
}
</style>
<script>
function addInputs() {
const parentDiv = document.getElementById("d1");
const textField = document.createElement("input");
textField.type = "text";
textField.value = "Enter content";
const pwdField = document.createElement("input");
pwdField.type = "password";
pwdField.value = "123456789";
const deleteBtn = document.createElement("input");
deleteBtn.type = "button";
deleteBtn.value = "Remove";
const lineBreak = document.createElement("br");
deleteBtn.onclick = function () {
parentDiv.removeChild(textField);
parentDiv.removeChild(pwdField);
parentDiv.removeChild(deleteBtn);
parentDiv.removeChild(lineBreak);
};
parentDiv.appendChild(textField);
parentDiv.appendChild(pwdField);
parentDiv.appendChild(deleteBtn);
parentDiv.appendChild(lineBreak);
}
</script>
</head>
<body>
<div id="d1"></div>
<input type="button" value="Add Inputs" onclick="addInputs()" />
</body>
</html>