JsGuide

Learn JavaScript with practical tutorials and code examples

Code Snippet intermediate
javascript• Updated Jan 18, 2024

DOM Utility Functions - Essential JavaScript Snippets

Collection of useful DOM manipulation utility functions for common web development tasks. Copy-paste ready JavaScript code snippets.

DOM Utility Functions - Essential JavaScript Snippets

A collection of useful DOM manipulation utility functions that you can copy and paste into your projects. These functions solve common web development tasks and provide clean, reusable code.

Element Selection Utilities #

$ - jQuery-style Element Selection #

// Simple element selection with optional parent context
function $(selector, parent = document) {
    return parent.querySelector(selector);
}

function $$(selector, parent = document) {
    return Array.from(parent.querySelectorAll(selector));
}

// Usage
const button = $('#myButton');
const allParagraphs = $$('p');
const navItems = $$('li', $('#navigation'));

Element Existence Checker #

// Check if element exists before performing operations
function elementExists(selector) {
    return document.querySelector(selector) !== null;
}

// Usage
if (elementExists('#myModal')) {
    $('#myModal').classList.add('visible');
}

Wait for Element to Exist #

// Wait for an element to appear in the DOM
function waitForElement(selector, timeout = 10000) {
    return new Promise((resolve, reject) => {
        const element = document.querySelector(selector);
        if (element) {
            resolve(element);
            return;
        }
        
        const observer = new MutationObserver((mutations) => {
            const element = document.querySelector(selector);
            if (element) {
                observer.disconnect();
                resolve(element);
            }
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        
        setTimeout(() => {
            observer.disconnect();
            reject(new Error(`Element ${selector} not found within ${timeout}ms`));
        }, timeout);
    });
}

// Usage
waitForElement('#dynamicContent')
    .then(element => {
        console.log('Element found:', element);
    })
    .catch(error => {
        console.error('Element not found:', error);
    });

Element Creation Utilities #

Create Element with Attributes #

// Create element with attributes and content
function createElement(tagName, attributes = {}, content = '') {
    const element = document.createElement(tagName);
    
    // Set attributes
    Object.entries(attributes).forEach(([key, value]) => {
        if (key === 'className') {
            element.className = value;
        } else if (key === 'textContent') {
            element.textContent = value;
        } else if (key === 'innerHTML') {
            element.innerHTML = value;
        } else {
            element.setAttribute(key, value);
        }
    });
    
    // Set content if provided
    if (content) {
        element.textContent = content;
    }
    
    return element;
}

// Usage
const button = createElement('button', {
    className: 'btn btn-primary',
    id: 'myButton',
    'data-action': 'submit'
}, 'Click me');

const div = createElement('div', {
    className: 'container',
    innerHTML: '<p>Hello World</p>'
});

Create Element from HTML String #

// Create element from HTML string
function createElementFromHTML(htmlString) {
    const template = document.createElement('template');
    template.innerHTML = htmlString.trim();
    return template.content.firstChild;
}

// Usage
const element = createElementFromHTML(`
    <div class="card">
        <h3>Card Title</h3>
        <p>Card content</p>
    </div>
`);

CSS Class Utilities #

Toggle Multiple Classes #

// Toggle multiple classes on an element
function toggleClasses(element, ...classes) {
    classes.forEach(className => {
        element.classList.toggle(className);
    });
}

// Usage
toggleClasses(button, 'active', 'highlighted', 'important');

Has Any Class #

// Check if element has any of the specified classes
function hasAnyClass(element, ...classes) {
    return classes.some(className => element.classList.contains(className));
}

// Usage
if (hasAnyClass(element, 'active', 'selected', 'highlighted')) {
    console.log('Element has at least one of the classes');
}

Replace Class #

// Replace a class with another class
function replaceClass(element, oldClass, newClass) {
    if (element.classList.contains(oldClass)) {
        element.classList.remove(oldClass);
        element.classList.add(newClass);
    }
}

// Usage
replaceClass(button, 'btn-primary', 'btn-success');

Event Utilities #

One-time Event Listener #

// Add event listener that only fires once
function once(element, event, callback) {
    const handler = (e) => {
        callback(e);
        element.removeEventListener(event, handler);
    };
    element.addEventListener(event, handler);
}

// Usage
once(button, 'click', () => {
    console.log('This will only run once');
});

Event Delegation #

// Event delegation utility
function delegate(parent, childSelector, eventType, callback) {
    parent.addEventListener(eventType, (e) => {
        if (e.target.matches(childSelector)) {
            callback(e);
        }
    });
}

// Usage
delegate(document.body, '.delete-btn', 'click', (e) => {
    e.target.closest('.item').remove();
});

Throttle and Debounce for Events #

// Throttle function - limits how often a function can be called
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// Debounce function - delays execution until after wait time
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Usage
const scrollHandler = throttle(() => {
    console.log('Scrolling...');
}, 100);

const searchHandler = debounce((query) => {
    console.log('Searching for:', query);
}, 300);

window.addEventListener('scroll', scrollHandler);
document.getElementById('search').addEventListener('input', (e) => {
    searchHandler(e.target.value);
});

Style Utilities #

Get Computed Style Value #

// Get computed style value for an element
function getStyleValue(element, property) {
    return window.getComputedStyle(element).getPropertyValue(property);
}

// Usage
const fontSize = getStyleValue(element, 'font-size');
const backgroundColor = getStyleValue(element, 'background-color');

Set Multiple Styles #

// Set multiple styles at once
function setStyles(element, styles) {
    Object.entries(styles).forEach(([property, value]) => {
        element.style[property] = value;
    });
}

// Usage
setStyles(element, {
    color: 'red',
    fontSize: '18px',
    backgroundColor: 'yellow',
    padding: '10px'
});

Toggle Visibility #

// Toggle element visibility
function toggleVisibility(element) {
    const isVisible = element.style.display !== 'none';
    element.style.display = isVisible ? 'none' : 'block';
}

// Show element
function show(element) {
    element.style.display = 'block';
}

// Hide element
function hide(element) {
    element.style.display = 'none';
}

// Usage
toggleVisibility(modal);
show(tooltip);
hide(overlay);

Form Utilities #

Get Form Data as Object #

// Convert form data to JavaScript object
function getFormData(form) {
    const formData = new FormData(form);
    const data = {};
    
    for (let [key, value] of formData.entries()) {
        if (data[key]) {
            // Handle multiple values (like checkboxes)
            if (Array.isArray(data[key])) {
                data[key].push(value);
            } else {
                data[key] = [data[key], value];
            }
        } else {
            data[key] = value;
        }
    }
    
    return data;
}

// Usage
const form = document.getElementById('myForm');
const formData = getFormData(form);
console.log(formData);

Validate Form Field #

// Simple form validation
function validateField(field, rules) {
    const value = field.value.trim();
    const errors = [];
    
    if (rules.required && !value) {
        errors.push('This field is required');
    }
    
    if (rules.minLength && value.length < rules.minLength) {
        errors.push(`Minimum length is ${rules.minLength}`);
    }
    
    if (rules.maxLength && value.length > rules.maxLength) {
        errors.push(`Maximum length is ${rules.maxLength}`);
    }
    
    if (rules.pattern && !rules.pattern.test(value)) {
        errors.push('Invalid format');
    }
    
    return errors;
}

// Usage
const emailField = document.getElementById('email');
const errors = validateField(emailField, {
    required: true,
    pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
});

if (errors.length > 0) {
    console.log('Validation errors:', errors);
}

Animation Utilities #

Fade In/Out #

// Fade in element
function fadeIn(element, duration = 300) {
    element.style.opacity = '0';
    element.style.display = 'block';
    
    const start = performance.now();
    
    function animate(currentTime) {
        const elapsed = currentTime - start;
        const progress = Math.min(elapsed / duration, 1);
        
        element.style.opacity = progress;
        
        if (progress < 1) {
            requestAnimationFrame(animate);
        }
    }
    
    requestAnimationFrame(animate);
}

// Fade out element
function fadeOut(element, duration = 300) {
    const start = performance.now();
    const initialOpacity = parseFloat(element.style.opacity) || 1;
    
    function animate(currentTime) {
        const elapsed = currentTime - start;
        const progress = Math.min(elapsed / duration, 1);
        
        element.style.opacity = initialOpacity * (1 - progress);
        
        if (progress >= 1) {
            element.style.display = 'none';
        } else {
            requestAnimationFrame(animate);
        }
    }
    
    requestAnimationFrame(animate);
}

// Usage
fadeIn(modal);
setTimeout(() => fadeOut(modal), 2000);

Slide Up/Down #

// Slide up element
function slideUp(element, duration = 300) {
    const height = element.offsetHeight;
    element.style.height = height + 'px';
    element.style.overflow = 'hidden';
    
    const start = performance.now();
    
    function animate(currentTime) {
        const elapsed = currentTime - start;
        const progress = Math.min(elapsed / duration, 1);
        
        element.style.height = height * (1 - progress) + 'px';
        
        if (progress >= 1) {
            element.style.display = 'none';
            element.style.height = '';
            element.style.overflow = '';
        } else {
            requestAnimationFrame(animate);
        }
    }
    
    requestAnimationFrame(animate);
}

// Slide down element
function slideDown(element, duration = 300) {
    element.style.display = 'block';
    const height = element.scrollHeight;
    element.style.height = '0px';
    element.style.overflow = 'hidden';
    
    const start = performance.now();
    
    function animate(currentTime) {
        const elapsed = currentTime - start;
        const progress = Math.min(elapsed / duration, 1);
        
        element.style.height = height * progress + 'px';
        
        if (progress >= 1) {
            element.style.height = '';
            element.style.overflow = '';
        } else {
            requestAnimationFrame(animate);
        }
    }
    
    requestAnimationFrame(animate);
}

Position and Dimension Utilities #

Get Element Position #

// Get element position relative to document
function getElementPosition(element) {
    const rect = element.getBoundingClientRect();
    return {
        x: rect.left + window.scrollX,
        y: rect.top + window.scrollY,
        width: rect.width,
        height: rect.height
    };
}

// Usage
const position = getElementPosition(button);
console.log(`Element is at (${position.x}, ${position.y})`);

Check if Element is in Viewport #

// Check if element is visible in viewport
function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

// Usage
if (isInViewport(element)) {
    console.log('Element is visible');
}

Scroll to Element #

// Scroll to element with smooth animation
function scrollToElement(element, offset = 0) {
    const elementPosition = element.getBoundingClientRect().top + window.scrollY;
    const targetPosition = elementPosition + offset;
    
    window.scrollTo({
        top: targetPosition,
        behavior: 'smooth'
    });
}

// Usage
scrollToElement(document.getElementById('section'), -100);

Utility Helper Functions #

Wait for DOM Ready #

// Wait for DOM to be ready
function domReady(callback) {
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', callback);
    } else {
        callback();
    }
}

// Usage
domReady(() => {
    console.log('DOM is ready');
    // Initialize your app
});

Copy to Clipboard #

// Copy text to clipboard
async function copyToClipboard(text) {
    try {
        await navigator.clipboard.writeText(text);
        console.log('Text copied to clipboard');
    } catch (err) {
        // Fallback for older browsers
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.opacity = '0';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        
        try {
            document.execCommand('copy');
            console.log('Text copied to clipboard (fallback)');
        } catch (err) {
            console.error('Failed to copy text: ', err);
        }
        
        document.body.removeChild(textArea);
    }
}

// Usage
copyToClipboard('Hello World');

Get Unique ID #

// Generate unique ID for elements
function generateUniqueId(prefix = 'id') {
    return `${prefix}-${Math.random().toString(36).substr(2, 9)}`;
}

// Usage
const uniqueId = generateUniqueId('button');
button.id = uniqueId;

Complete Example: Modal Utility #

// Complete modal utility class
class Modal {
    constructor(options = {}) {
        this.options = {
            closable: true,
            backdrop: true,
            keyboard: true,
            ...options
        };
        
        this.modal = null;
        this.isOpen = false;
        this.onClose = null;
        this.onOpen = null;
        
        this.init();
    }
    
    init() {
        this.modal = createElement('div', {
            className: 'modal',
            innerHTML: `
                <div class="modal-backdrop"></div>
                <div class="modal-content">
                    ${this.options.closable ? '<button class="modal-close">&times;</button>' : ''}
                    <div class="modal-body"></div>
                </div>
            `
        });
        
        document.body.appendChild(this.modal);
        this.bindEvents();
    }
    
    bindEvents() {
        if (this.options.closable) {
            const closeBtn = this.modal.querySelector('.modal-close');
            closeBtn.addEventListener('click', () => this.close());
        }
        
        if (this.options.backdrop) {
            const backdrop = this.modal.querySelector('.modal-backdrop');
            backdrop.addEventListener('click', () => this.close());
        }
        
        if (this.options.keyboard) {
            document.addEventListener('keydown', (e) => {
                if (e.key === 'Escape' && this.isOpen) {
                    this.close();
                }
            });
        }
    }
    
    open(content) {
        const body = this.modal.querySelector('.modal-body');
        body.innerHTML = content;
        
        this.modal.classList.add('active');
        this.isOpen = true;
        
        if (this.onOpen) {
            this.onOpen();
        }
    }
    
    close() {
        this.modal.classList.remove('active');
        this.isOpen = false;
        
        if (this.onClose) {
            this.onClose();
        }
    }
    
    destroy() {
        this.modal.remove();
    }
}

// Usage
const modal = new Modal({
    closable: true,
    backdrop: true,
    keyboard: true
});

modal.onOpen = () => console.log('Modal opened');
modal.onClose = () => console.log('Modal closed');

modal.open('<h2>Hello World</h2><p>This is a modal dialog.</p>');

CSS for Utilities #

/* Modal styles */
.modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
}

.modal.active {
    display: flex;
    align-items: center;
    justify-content: center;
}

.modal-backdrop {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
    position: relative;
    background: white;
    padding: 2rem;
    border-radius: 8px;
    max-width: 90%;
    max-height: 90%;
    overflow: auto;
}

.modal-close {
    position: absolute;
    top: 10px;
    right: 15px;
    background: none;
    border: none;
    font-size: 1.5rem;
    cursor: pointer;
}

/* Animation utilities */
.fade-in {
    animation: fadeIn 0.3s ease-in-out;
}

.fade-out {
    animation: fadeOut 0.3s ease-in-out;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes fadeOut {
    from { opacity: 1; }
    to { opacity: 0; }
}

Usage Tips #

  1. Bundle commonly used utilities into a single file
  2. Use ES6 modules to import only what you need
  3. Add error handling for production use
  4. Consider browser compatibility for your target audience
  5. Test utilities thoroughly across different scenarios

These utility functions provide a solid foundation for DOM manipulation in your JavaScript projects. Copy and customize them based on your specific needs!

Next Steps #

Related Snippets

Snippet Beginner

How to Fix JavaScript Error: Ready-to-Use Utilities

Practical JavaScript code snippets and utilities to quickly fix common JavaScript errors with copy-paste solutions.

#javascript #error #fix +2
View Code
Syntax
Snippet Beginner

What Are JavaScript Data Types: Detection Utility Functions

Ready-to-use JavaScript utility functions to detect and validate data types with examples for all JavaScript data types.

#javascript #data-types #utilities +2
View Code
Syntax
Snippet intermediate

JavaScript Array Methods - Complete Cheat Sheet

Master JavaScript array methods with practical examples. From map and filter to reduce and forEach, learn all essential array manipulation techniques.

#javascript #arrays #methods +2
View Code
snippets
Snippet Intermediate

JavaScript Code Snippets: Fix 'ipython is not defined' Error

Ready-to-use JavaScript code snippets to handle and fix 'ipython is not defined' errors in Jupyter notebooks and web environments.

#javascript #ipython #error-handling +2
View Code
Syntax