DOM CRUD Operations

The Document Object Model (DOM) is a tree structure for your HTML. JavaScript uses it to access and change every element, attribute, and text piece on a page.

When you click a button and the page updates without a refresh, you see DOM manipulation in action.

Here is how you perform CRUD (Create, Read, Update, Delete) operations.

  1. Read: Accessing Elements Use these methods to find elements on your page:
  • getElementById()
  • getElementsByClassName()
  • getElementsByTagName()
  • querySelector()
  • querySelectorAll()
  1. Create: Making New Elements You can generate new HTML elements using JavaScript.
  • createElement(): Creates a new tag in memory.
  • append(): Adds content to the end of a parent.
  • appendChild(): Adds a single node as the last child.
  • prepend(): Adds content to the start of a parent.
  • before(): Inserts an element before a specific target.
  • after(): Inserts an element after a specific target.
  • insertBefore(): Places a new element before an existing child.
  1. Update: Changing Content Modify what users see on the screen:
  • innerText: Updates only the visible text.
  • textContent: Updates all text, including hidden text.
  • innerHTML: Updates content and allows you to add HTML tags.
  1. Attributes: Managing Properties Attributes add extra info to your tags.
  • setAttribute(): Sets a new value for an attribute. Note that this replaces the old value.
  • getAttribute(): Gets the current value.
  • removeAttribute(): Deletes an attribute.
  • hasAttribute(): Checks if an attribute exists.

Pro tip: Use classList.add() to add a class without deleting your current ones. Use setAttribute() for custom attributes.

  1. Delete: Removing Elements To remove an element from the page, use:
  • remove()

Summary of CRUD Flow:

  • Create: document.createElement("p")
  • Update: p.innerText = "Hello"
  • Read: document.getElementById("p")
  • Delete: p.remove()

Mastering these methods allows you to build interactive tools like to-do lists, calculators, and form validators. It is a vital step toward learning modern web frameworks.

Source: https://dev.to/madhanraj/document-object-model-dom-crud-operations-9ka

Optional learning community: https://t.me/GyaanSetuAi