Boost your productivity with these time-saving JavaScript code snippets. DOM manipulation, RegEx, Hidden Libraries and more.
function findParentWithClass(el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}
// 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);
}
function isIndianMobileNumber($phone = '') {
const regEx = /^[6-9]\d{9}$/gi;
return regEx.test($phone)
}
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]);
}
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
});
var activeElement = document.activeElement;
- EasyTimer.js