Master efficient DOM manipulation, event handling, and browser APIs without frameworks.
# Vanilla JavaScript DOM Best Practices
Master vanilla JavaScript DOM manipulation with Google Antigravity IDE. This comprehensive guide covers modern DOM APIs, event handling, and performance optimization for lightweight web applications.
## Why Vanilla JavaScript?
Vanilla JS provides direct DOM access without framework overhead. Google Antigravity IDE's Gemini 3 engine suggests optimal DOM patterns and identifies performance bottlenecks.
## Modern DOM Selection
```javascript
// Utility functions for DOM selection
const $ = (selector, context = document) => context.querySelector(selector);
const $$ = (selector, context = document) => [...context.querySelectorAll(selector)];
// Type-safe selection with error handling
function getElement(id) {
const element = document.getElementById(id);
if (!element) {
throw new Error(`Element with id "${id}" not found`);
}
return element;
}
// Scoped selection
function createScope(rootSelector) {
const root = $(rootSelector);
return {
$(selector) { return $(selector, root); },
$$(selector) { return $$(selector, root); },
};
}
// Usage
const modal = createScope("#modal");
const closeBtn = modal.$(".close-button");
const content = modal.$(".content");
```
## Event Delegation
```javascript
// Efficient event handling with delegation
class EventDelegator {
constructor(root) {
this.root = typeof root === "string" ? $(root) : root;
this.handlers = new Map();
}
on(eventType, selector, handler) {
if (!this.handlers.has(eventType)) {
this.handlers.set(eventType, []);
this.root.addEventListener(eventType, (event) => {
const handlers = this.handlers.get(eventType);
for (const { selector, handler } of handlers) {
const target = event.target.closest(selector);
if (target && this.root.contains(target)) {
handler.call(target, event, target);
}
}
});
}
this.handlers.get(eventType).push({ selector, handler });
return this;
}
off(eventType, selector) {
const handlers = this.handlers.get(eventType);
if (handlers) {
const index = handlers.findIndex((h) => h.selector === selector);
if (index > -1) handlers.splice(index, 1);
}
return this;
}
}
// Usage
const delegator = new EventDelegator("#app");
delegator
.on("click", ".btn-delete", (e, target) => {
const id = target.dataset.id;
deleteItem(id);
})
.on("click", ".btn-edit", (e, target) => {
const id = target.dataset.id;
editItem(id);
});
```
## DOM Manipulation Utilities
```javascript
// Create elements with attributes and children
function createElement(tag, attrs = {}, ...children) {
const element = document.createElement(tag);
for (const [key, value] of Object.entries(attrs)) {
if (key === "class") {
element.className = Array.isArray(value) ? value.join(" ") : value;
} else if (key === "style" && typeof value === "object") {
Object.assign(element.style, value);
} else if (key.startsWith("on") && typeof value === "function") {
element.addEventListener(key.slice(2).toLowerCase(), value);
} else if (key.startsWith("data-")) {
element.dataset[key.slice(5)] = value;
} else {
element.setAttribute(key, value);
}
}
for (const child of children) {
if (typeof child === "string") {
element.appendChild(document.createTextNode(child));
} else if (child instanceof Node) {
element.appendChild(child);
}
}
return element;
}
// Usage
const card = createElement(
"div",
{ class: "card", "data-id": "123" },
createElement("h2", { class: "title" }, "Card Title"),
createElement("p", { class: "content" }, "Card content goes here"),
createElement(
"button",
{ class: "btn", onClick: () => console.log("Clicked!") },
"Click Me"
)
);
```
## Batch DOM Updates
```javascript
// Use DocumentFragment for batch inserts
function renderList(items, container) {
const fragment = document.createDocumentFragment();
for (const item of items) {
const li = createElement(
"li",
{ class: "list-item", "data-id": item.id },
item.name
);
fragment.appendChild(li);
}
container.innerHTML = "";
container.appendChild(fragment);
}
// Use requestAnimationFrame for visual updates
function animateElement(element, properties, duration) {
const start = performance.now();
const initial = {};
for (const prop of Object.keys(properties)) {
initial[prop] = parseFloat(getComputedStyle(element)[prop]) || 0;
}
function update(currentTime) {
const elapsed = currentTime - start;
const progress = Math.min(elapsed / duration, 1);
for (const [prop, target] of Object.entries(properties)) {
const value = initial[prop] + (target - initial[prop]) * progress;
element.style[prop] = `${value}px`;
}
if (progress < 1) {
requestAnimationFrame(update);
}
}
requestAnimationFrame(update);
}
```
## Intersection Observer
```javascript
// Lazy loading with Intersection Observer
function lazyLoad(selector, callback) {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
callback(entry.target);
observer.unobserve(entry.target);
}
});
},
{ rootMargin: "100px", threshold: 0.1 }
);
$$(selector).forEach((el) => observer.observe(el));
return observer;
}
// Usage - lazy load images
lazyLoad("img[data-src]", (img) => {
img.src = img.dataset.src;
img.classList.add("loaded");
});
```
## Best Practices
- Use event delegation for dynamic content
- Batch DOM updates with DocumentFragment
- Use requestAnimationFrame for animations
- Leverage Intersection Observer for lazy loading
- Cache DOM references for repeated access
- Use template literals for complex HTML
Google Antigravity IDE provides vanilla JavaScript patterns and suggests modern APIs for optimal DOM manipulation.This JavaScript prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their javascript implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For JavaScript projects, consider mentioning your framework version, coding style, and any specific libraries you're using.