DOM CRUD Operations

The Document Object Model (DOM) is how browsers represent HTML. It turns every element, attribute, and text piece into an object. JavaScript uses these objects to change what you see on a screen.

When you click a button and a page updates without refreshing, JavaScript is changing the DOM.

You can perform CRUD (Create, Read, Update, Delete) operations with these methods.

  1. Accessing Elements (Read) To change something, you must first find it. Use these methods:
  • getElementById()
  • getElementsByClassName()
  • getElementsByTagName()
  • querySelector()
  • querySelectorAll()
  1. Creating Elements (Create) You can generate new HTML elements using JavaScript.
  • createElement("tagName") creates the element 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 item.
  • after() inserts an element after a specific item.
  • insertBefore() places an element before a specific child.

Note: An element stays in memory until you add it to the page.

  1. Updating Elements (Update) You can change existing content using these properties:
  • innerText: Changes only visible text.
  • textContent: Changes all text, including hidden text.
  • innerHTML: Changes content and allows you to add HTML tags.
  1. Working with Attributes (Update) Attributes provide extra info about elements.
  • setAttribute(name, value): Sets or replaces an attribute.
  • getAttribute(name): Retrieves an attribute value.
  • removeAttribute(name): Deletes an attribute.
  • hasAttribute(name): Checks if an attribute exists.

Pro tip: Use classList.add() to add a class without removing old ones. setAttribute() replaces the entire value.

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

Summary of a CRUD flow:

  • Create: createElement()
  • Update: innerText = "New text"
  • Add: appendChild()
  • Delete: remove()

Mastering these methods allows you to build interactive apps like to-do lists or calculators. This is a vital skill for front-end development.

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