Document Object Model [DOM] CRUD Operations

java dev.to

Introduction to DOM Manipulation

The Document Object Model (DOM) is a programming interface provided by the browser that represents an HTML document as a tree-like structure. Every HTML element, attribute, and piece of text becomes an object that JavaScript can access and manipulate.
Using DOM manipulation, We can:

Access HTML elements

Create new elements

Update existing content

Add or remove attributes

Delete elements dynamically

Build interactive web applications
For example, when you click a button and the webpage updates without refreshing, JavaScript is usually manipulating the DOM behind the scenes.
Enter fullscreen mode Exit fullscreen mode

1. Accessing Elements

 getElementById()
    getElementsByClassName()
    getElementsByTagName()
    querySelector()
    querySelectorAll()

Enter fullscreen mode Exit fullscreen mode

These are the main DOM element selection (accessing) methods in JavaScript.
Before modifying an element, we must first access it from the DOM.
2. Creating Elements

Creating elements means generating new HTML elements dynamically using JavaScript.

createElement()

Enter fullscreen mode Exit fullscreen mode

Creates a new HTML element.
Syntax

document.createElement("tagName");

Example

const heading = document.createElement("h1");

heading.innerText = "Welcome to My Website";

console.log(heading);

Enter fullscreen mode Exit fullscreen mode

Output

<h1>Welcome to My Website</h1>
Enter fullscreen mode Exit fullscreen mode

Note: The element is created in memory and will not appear on the page until it is added to the DOM.
3. Adding Elements

After creating an element, it must be inserted into the webpage.
append()

Adds content at the end of a parent element.
Example

const container = document.getElementById("container");

const p = document.createElement("p");
p.innerText = "New Paragraph";

container.append(p);

Enter fullscreen mode Exit fullscreen mode

Paragraph is added as the last child of that Container.
appendChild()

Adds a single node as the last child of a parent element.
Example


const list = document.getElementById("list");

const li = document.createElement("li");
li.innerText = "Apple";

list.appendChild(li);
Enter fullscreen mode Exit fullscreen mode

Adds the list item at the end.
prepend()

Adds content at the beginning of a parent element.
Example

const container = document.getElementById("container");

const h1 = document.createElement("h1");
h1.innerText = "Welcome";

container.prepend(h1);

Enter fullscreen mode Exit fullscreen mode

Heading appears before all existing children.
before()

Inserts an element before another element.
Example

const para = document.getElementById("para");

const heading = document.createElement("h2");
heading.innerText = "Article Title";

para.before(heading);
Enter fullscreen mode Exit fullscreen mode

Heading appears before the paragraph.
after()

Inserts an element after another element.
Example

const para = document.getElementById("para");

const button = document.createElement("button");
button.innerText = "Read More";

para.after(button);
Enter fullscreen mode Exit fullscreen mode

Button appears after the paragraph.
insertBefore()

Inserts a new element before a specified child element.
Example

const ul = document.getElementById("list");

const newItem = document.createElement("li");
newItem.innerText = "Mango";

const firstItem = ul.children[0];

ul.insertBefore(newItem, firstItem);

Enter fullscreen mode Exit fullscreen mode

Mango becomes the first list item.

Use appendChild() when adding one element node.
Use append() when you want to add multiple elements or text in a single statement.
append() Adding multiple Element


<div id="container"></div>

const container = document.getElementById("container");

const h1 = document.createElement("h1");
h1.innerText = "Title";

const p = document.createElement("p");
p.innerText = "Paragraph";

container.append(h1, p);
Enter fullscreen mode Exit fullscreen mode

Output

<div id="container">
    <h1>Title</h1>
    <p>Paragraph</p>
</div>
Enter fullscreen mode Exit fullscreen mode

You cannot do this with appendChild().
4. Updating Elements

Updating elements means changing the content of existing HTML elements.
innerText

Returns or updates only the visible text.
Example

<p id="text">Hello World</p>

<script>
document.getElementById("text").innerText = "Welcome";
</script>
Enter fullscreen mode Exit fullscreen mode

Output

Welcome

textContent

Returns or updates all text content, including hidden text.
Example

<p id="text">Hello World</p>

<script>
document.getElementById("text").textContent = "JavaScript DOM";
</script>

Enter fullscreen mode Exit fullscreen mode

Output

JavaScript DOM

innerHTML

Enter fullscreen mode Exit fullscreen mode

Returns or updates HTML content inside an element.
Example

<div id="box"></div>

<script>
document.getElementById("box").innerHTML =
"<h2>Welcome</h2><p>This is a paragraph.</p>";
</script>
Enter fullscreen mode Exit fullscreen mode

Output

Welcome
This is a paragraph.

Enter fullscreen mode Exit fullscreen mode

Note: innerHTML can add HTML tags, while innerText and textContent add only plain text.
5. Working with Attributes

Attributes provide additional information about HTML elements.
setAttribute()

Adds or updates an attribute.
Example

const image = document.getElementById("photo");

image.setAttribute("src", "image.jpg");
Enter fullscreen mode Exit fullscreen mode

Output

<img src="image.jpg">

getAttribute()

Enter fullscreen mode Exit fullscreen mode

Gets the value of an attribute.
Example

const image = document.getElementById("photo");

console.log(image.getAttribute("src"));
Enter fullscreen mode Exit fullscreen mode

Example

const image = document.getElementById("photo");

image.removeAttribute("src");

Output

<img>

hasAttribute()

Enter fullscreen mode Exit fullscreen mode

Checks whether an attribute exists.
Example

const image = document.getElementById("photo");

console.log(image.hasAttribute("src"));

Enter fullscreen mode Exit fullscreen mode

Output

true

setAttribute() does not append values to an existing attribute. It sets the attribute to the exact value you provide.

Syntax

element.setAttribute(attributeName, value);

With id

Example

<p id="para">Hello</p>

const p = document.getElementById("para");

p.setAttribute("id", "message");
Enter fullscreen mode Exit fullscreen mode

Output


<p id="message">Hello</p>

The old id="para" is replaced by id="message".
Enter fullscreen mode Exit fullscreen mode

Since an element should have only one ID, the previous ID is overwritten.
With class

Example

<p class="text">Hello</p>

const p = document.querySelector("p");

p.setAttribute("class", "heading");

Enter fullscreen mode Exit fullscreen mode

Output

<p class="heading">Hello</p>
Enter fullscreen mode Exit fullscreen mode

The old class text is removed and replaced with heading.
Multiple Classes

Suppose you have:

<p class="text">Hello</p>

p.setAttribute("class", "text active");

Enter fullscreen mode Exit fullscreen mode

Output

<p class="text active">Hello</p>

Enter fullscreen mode Exit fullscreen mode

Now the element has two classes:

text

active
But notice that you're still replacing the entire class attribute value with "text active".
Enter fullscreen mode Exit fullscreen mode

If You Want to Add a Class Without Removing Existing Ones
Use classList.add()
Example

<p class="text">Hello</p>

p.classList.add("active");

Enter fullscreen mode Exit fullscreen mode

Output

<p class="text active">Hello</p>
Enter fullscreen mode Exit fullscreen mode

Here the existing class text remains, and active is added.

setAttribute() replaces the entire attribute value. It does not merge or append automatically. For classes, classList is usually the better choice when you want to add or remove classes dynamically.
Enter fullscreen mode Exit fullscreen mode

We can do the same things simply without using these functions.
Changing an ID

<p id="para">Hello</p>

const p = document.getElementById("para");

p.id = "message";

**Output**

<p id="message">Hello</p>

Removing an ID

p.id = "";
Enter fullscreen mode Exit fullscreen mode

Output


<p>Hello</p>

Changing a Class

<p class="text">Hello</p>

p.className = "heading";
Enter fullscreen mode Exit fullscreen mode

Output

<p class="heading">Hello</p>

Adding Multiple Classes

p.className = "text active";

Enter fullscreen mode Exit fullscreen mode

Output

<p class="text active">Hello</p>

Removing All Classes

p.className = "";
Enter fullscreen mode Exit fullscreen mode

Output

<p>Hello</p>
Enter fullscreen mode Exit fullscreen mode
For common attributes (id, class, src, href, value), developers usually use the property approach because it's shorter and easier to read. setAttribute() and removeAttribute() are more useful when working with custom attributes.
Enter fullscreen mode Exit fullscreen mode

6. Removing Elements

Removing elements means deleting HTML elements from the DOM.
remove()

Removes an element from the webpage.
Example


<p id="message">This message will be removed.</p>

<script>
const msg = document.getElementById("message");

msg.remove();
</script>
Enter fullscreen mode Exit fullscreen mode

The paragraph is completely removed from the webpage.
DOM CRUD Operations Summary

CRUD stands for Create, Read, Update, and Delete.

Example CRUD Flow

// Create
const p = document.createElement("p");

// Update
p.innerText = "Hello DOM";

// Add to page
document.body.appendChild(p);

// Delete
p.remove();
Enter fullscreen mode Exit fullscreen mode

DOM Manipulation is one of the most important concepts in JavaScript because it allows developers to interact with and modify web pages dynamically. By learning how to access, create, add, update, and remove elements, you can build interactive applications such as to-do lists, calculators, form validators, and many other modern web projects. Mastering these DOM methods is a strong foundation for learning advanced JavaScript frameworks and front-end development.
References

Source: dev.to

arrow_back Back to Tutorials