275 个最喜欢的JavaScript实用工具

DOM
const isDescendant = (child, parent) => parent.contains(child);
const hasFocus = (ele) => ele === document.activeElement;
const touchSupported = () =>
"ontouchstart" in window ||
(window.DocumentTouch && document instanceof window.DocumentTouch);
const isAtBottom = () =>
document.documentElement.clientHeight + window.scrollY >=
document.documentElement.scrollHeight;
const isIE = !!document.documentMode;
const isMacBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
const siblings = (ele) =>
[].slice.call(ele.parentNode.children).filter((child) => child !== ele);
const getPosition = (ele) => (
(r = ele.getBoundingClientRect()),
{ left: r.left + window.scrollX, top: r.top + window.scrollY }
);

// Example
getPosition(document.body); // { left: 0, top: 0 }
const getSelectedText = () => window.getSelection().toString();
history.back();

// Or
history.go(-1);
// Pick the method that is suitable for your use case
const hide = (ele) => (ele.style.display = "none");

// Or
const hide = (ele) => (ele.style.visibility = "hidden");

// Or
const hide = (ele) => (ele.hidden = true);
const insertAfter = (ele, anotherEle) =>
anotherEle.parentNode.insertBefore(ele, anotherEle.nextSibling);

// Or
const insertAfter = (ele, anotherEle) =>
anotherEle.insertAdjacentElement("afterend", ele);
const insertBefore = (ele, anotherEle) =>
anotherEle.parentNode.insertBefore(ele, anotherEle);

// Or
const insertBefore = (ele, anotherEle) =>
anotherEle.insertAdjacentElement("beforebegin", ele);
const insertHtmlAfter = (html, ele) => ele.insertAdjacentHTML("afterend", html);
const insertHtmlBefore = (html, ele) =>
ele.insertAdjacentHTML("beforebegin", html);
const goTo = (url) => (location.href = url);
const reload = () => location.reload();

// Or
const reload = () => (location.href = location.href);
const replace = (ele, newEle) => ele.parentNode.replaceChild(newEle, ele);
const goToTop = () => window.scrollTo(0, 0);
const serialize = (formEle) =>
Array.from(new FormData(formEle)).reduce(
(p, [k, v]) =>
Object.assign({}, p, {
[k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v,
}),
{}
);
const show = (ele) => (ele.style.display = "");
const stripHtml = (html) =>
new DOMParser().parseFromString(html, "text/html").body.textContent || "";
const toggle = (ele) =>
(ele.style.display = ele.style.display === "none" ? "block" : "none");

// Or
const toggle = (ele) => (ele.hidden = !ele.hidden);