DEV Community

vishwa v
vishwa v

Posted on

dom-crud

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>

Enter fullscreen mode Exit fullscreen mode

Top comments (0)