DEV Community

Ali Al Khawaja
Ali Al Khawaja

Posted on

DOM Manipulation Refresher - AI written

1. Selecting Elements

// By ID
const element = document.getElementById('content');
// By class (returns NodeList)
const elements = document.getElementsByClassName('my-class');
// By tag (returns HTMLCollection)
const divs = document.getElementsByTagName('div');
// Modern selectors (returns first match)
const element = document.querySelector('#content p.intro');
// Returns NodeList of all matches
const elements = document.querySelectorAll('.items');
Enter fullscreen mode Exit fullscreen mode

2. Modifying Content

// Replace all content (parses HTML)
element.innerHTML = '<strong>New content</strong>';

// Just text (safer against XSS)
element.textContent = 'Plain text content';

// For form elements
inputElement.value = 'New value';
Enter fullscreen mode Exit fullscreen mode

3. Creating and Adding Elements

// Create new element
const newParagraph = document.createElement('p');
newParagraph.textContent = 'A new paragraph';

// Append to end
contentDiv.appendChild(newParagraph);

// Insert before another element
contentDiv.insertBefore(newParagraph, existingElement);

// Insert adjacent HTML (more flexible)
contentDiv.insertAdjacentHTML('beforeend', '<p>New paragraph</p>');
// Positions: 'beforebegin', 'afterbegin', 'beforeend', 'afterend'
Enter fullscreen mode Exit fullscreen mode

4. Best Practice Example

// Instead of innerHTML (which can have security risks), you can:
const contentDiv = document.getElementById('content');

// Clear existing content
while (contentDiv.firstChild) {
    contentDiv.removeChild(contentDiv.firstChild);
}

// Create and append new elements
const heading = document.createElement('h2');
heading.textContent = 'Section Title';
contentDiv.appendChild(heading);

const paragraph = document.createElement('p');
paragraph.textContent = 'This is a paragraph of text.';
contentDiv.appendChild(paragraph);
Enter fullscreen mode Exit fullscreen mode

5. Event Handling

contentDiv.addEventListener('click', function(event) {
    console.log('Div was clicked!', event);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
dotallio profile image
Dotallio

Super handy refresher! I always come back to these basics when building anything serious. Any plans to cover reactive or AI-powered DOM approaches next?

Collapse
 
ali-alkhawaja profile image
Ali Al Khawaja

Maybe in the future, it depends, I write posts when there is a need, like this post .
I just haven't coded any JS for like three months or so and I forgot the basics , made a refresher with help of AI and noticed that it did really remind me of the basic, so I just posted it 🤷‍♂️ , I'm actually surprised that someone read it

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

Pretty cool, I always need a refresher like this when my brain blanks on the basics

Some comments may only be visible to logged-in visitors. Sign in to view all comments.