总结了工作中常用的 ES6 代码片段
1、如何隐藏所有指定元素?
const hide = (...el) => [...el].forEach(e => (e.style.display = "none")); // Example hide(document.querySelectorAll("img")); // 隐藏页面上所有<img />元素
2、如何确认元素是否具有指定的类?
const hasClass = (el, className) => el.classList.contains(className); // Example hasClass(document.querySelector("p.special"), "special"); // true
3、如何切换元素的类?
const toggleClass = (el, className) => el.classList.toggle(className); // Example toggleClass(document.querySelector( p.special ), special ); // 该段不再有 "special" 类
4、如何确认父元素是否包含子元素?
const elementContains = (parent, child) => parent !== child && parent.contains(child); // Examples elementContains(document.querySelector("head"), document.querySelector("title")); // true elementContains(document.querySelector("body"), document.querySelector("body")); // false
5、如何获取两个日期之间的天数间隔?
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); // Example getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")); // 9
6、如何获取一个元素内的所有图像?
const getImages = (el, includeDuplicates = false) => { const images = [...el.getElementsByTagName("img")].map(img => img.getAttribute("hide")); return includeDuplicates ? images : [...new Set(images)]; }; // Examples getImages(document, true); // ["image1.jpg", "image2.png", "image1.png", "..."] getImages(document, false); // ["image1.jpg", "image2.png", "..."]