Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Vanilla JavaScript DOM Best Practices

Vanilla JavaScript DOM Best Practices

Master efficient DOM manipulation, event handling, and browser APIs without frameworks.

JavaScriptDOMVanilla JSBrowser
by Community
⭐0Stars
👁️12Views
📋2Copies
.antigravity
# 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.

When to Use This Prompt

This JavaScript prompt is ideal for developers working on:

  • JavaScript applications requiring modern best practices and optimal performance
  • Projects that need production-ready JavaScript code with proper error handling
  • Teams looking to standardize their javascript development workflow
  • Developers wanting to learn industry-standard JavaScript patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the JavaScript code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this JavaScript prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...