Complete website in Rs. 5,000 with Free Hosting & Domain. Offer ends in  00:00:00
Back to Blog

JavaScript Tips, Code Snippets and Libraries

Boost your productivity with these time-saving JavaScript code snippets. DOM manipulation, RegEx, Hidden Libraries and more.

May 5, 2023 Updated: May 5, 2023

Find the closest ancestor element that has a specific class in JavaScript

function findParentWithClass(el, cls) {
    while ((el = el.parentElement) && !el.classList.contains(cls));
    return el;
}

Remove all children from DOM element

// option 1: loop to remove every last child (preserve comments)
const myNode = document.getElementById("foo");
while (myNode.firstChild) {
    myNode.removeChild(myNode.lastChild);
}

// option 2: loop to remove every last element child (remove comments)
const myNode = document.getElementById("foo");
while (myNode.lastElementChild) {
    myNode.removeChild(myNode.lastElementChild);
}

Check if Mobile Number is Valid Indian Mobile Number in JavaScript

function isIndianMobileNumber($phone = '') {
    const regEx = /^[6-9]\d{9}$/gi;
    return regEx.test($phone)
}

Convert size in bytes to KB, MB, GB in JavaScript

function niceBytes(x){
    let units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    let l = 0, n = parseInt(x, 10) || 0;
    while(n >= 1024 && ++l){
        n = n/1024;
    }
    return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
}

Check if DOM is ready

function site_ready(callbackFunc) {
    if (document.readyState !== 'loading') {
        // Document is already ready, call the callback directly
        callbackFunc();
    } else if (document.addEventListener) {
        // All modern browsers to register DOMContentLoaded
        document.addEventListener('DOMContentLoaded', callbackFunc);
    } else {
        // Old IE browsers
        document.attachEvent('onreadystatechange', function () {
            if (document.readyState === 'complete') {
                callbackFunc();
            }
        });
    }
}
site_ready(function () {
    // your code here
});

Get Current Focused Element

var activeElement = document.activeElement;

Plugins

  1. EasyTimer.js
Contact

Got A Question For Us?

Feel free to ask anything directly on call or fill the form and we will contact back within few hours.