Create (Add new element)
<div id="container"></div>
<script>
let newPara = document.createElement("p");
newPara.textContent = "Hello, I am new!";
document.getElementById("container").appendChild(newPara);
or
document.getElementById("list").appendChild(item);
</script>
Adds a new
inside the container.
We use appendChild() or append() in JavaScript to add new elements or content into the DOM. Think of it like placing a new item inside a box β the box is your parent element, and the new item is the child element youβre adding.
Read (Access existing elements)
<p id="msg">Welcome to DOM CRUD</p>
<script>
let text = document.getElementById("msg").textContent;
console.log(text); // Output: Welcome to DOM CRUD
</script>
Reads the text of the element.
Update (Modify element content/attributes)
<p id="msg">Old Text</p>
<script>
let para = document.getElementById("msg");
para.textContent = "Updated Text";
para.style.color = "blue";
</script>
Updates both text and style.
Delete (Remove element)
<p id="msg">This will be deleted</p>
<script>
let para = document.getElementById("msg");
para.remove();
</script>
Removes the element completely from the DOM.
Adding blw element
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 id="ha">hi</h1>
<h1 id="eh">hello</h1>
<h2 id="One"></h2>
<button onclick="two()">submit</button>
<script>
function two() {
const element = document.getElementById("One");
element.innerText = "hello world!";
element.style.textAlign = "center";
const parent = document.body;
const referenceNode = document.getElementById("eh");
parent.insertBefore(element, referenceNode);
}
</script>
</body>
</html>
Top comments (0)