JavaScript DOM Manipulation

The DOM (Document Object Model) represents your page as a tree of nodes. Use JavaScript to select elements, read/change content, add/remove nodes, handle forms, and more.

1) Selecting Elements

Use getElementById, querySelector, and querySelectorAll.


<!-- HTML -->
<p id="title">Hello</p>
<div class="card">Item</div>

<!-- JS -->
const title = document.getElementById('title');
const firstCard = document.querySelector('.card');
const allCards = document.querySelectorAll('.card');

2) Text, HTML & Attributes

Use textContent/innerHTML for content, and getAttribute/setAttribute for attributes.


title.textContent = 'Welcome!';
firstCard.innerHTML = '<strong>Bold</strong> text';

const link = document.createElement('a');
link.setAttribute('href', 'https://codingwithsonu.com');
console.log(link.getAttribute('href'));

3) Classes & Inline Style

Toggle classes with classList. Change inline CSS via style (camelCase properties).


firstCard.classList.add('highlight');
firstCard.classList.toggle('active');
firstCard.style.backgroundColor = '#fffae6';

4) Create, Insert & Remove Elements

Create nodes with createElement and insert with append/prepend/before/after. Remove with remove.


const list = document.createElement('ul');
document.body.append(list);

const li = document.createElement('li');
li.textContent = 'Item 1';
list.append(li);

const li2 = document.createElement('li');
li2.textContent = 'Item 0';
list.prepend(li2); // goes to start

// remove
li.remove();

5) Traversing the DOM

Navigate relatives: parentElement, children, nextElementSibling, previousElementSibling.


const card = document.querySelector('.card');
console.log(card.parentElement);
console.log(card.children);
console.log(card.nextElementSibling);

6) Forms & Input Values

Read/write form fields via value. Use checked for checkboxes/radios and selectedIndex for selects.


<!-- HTML -->
<input id="name" placeholder="Your name">

<!-- JS -->
const nameInput = document.getElementById('name');
nameInput.value = 'Sonu';
console.log(nameInput.value);

7) Data Attributes (dataset)

Custom HTML attributes that start with data- become available on element.dataset.


<!-- HTML -->
<button id="buy" data-product-id="A123">Buy</button>

<!-- JS -->
const btn = document.getElementById('buy');
console.log(btn.dataset.productId); // "A123"
Tip: Query once and reuse references; avoid excessive querySelector calls inside loops. Prefer classes over inline styles for maintainability.