Returns true if the element has the specified class, false otherwise.
Use element.classList.contains() to check if the element has the specified class.
const hasClass = (el, className) => el.classList.contains(className);
hasClass(document.querySelector('p.special'), 'special'); // true
Hides all the elements specified.
Use the spread operator (...) and Array.forEach() to apply display: none to each element specified.
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none')); -
hide(document.querySelectorAll('img')); // Hides all <img> elements on the page +
hide(...document.querySelectorAll('img')); // Hides all <img> elements on the page
Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
Use location.protocol to get the protocol currently being used. If it's not HTTPS, use location.replace() to replace the existing page with the HTTPS version of the page. Use location.href to get the full address, split it with String.split() and remove the protocol part of the URL.
const httpsRedirect = () => { if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); }; @@ -460,7 +460,7 @@ document.body
Sets the value of a CSS rule for the specified element.
Use element.style to set the value of the CSS rule for the specified element to val.
const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);
setStyle(document.querySelector('p'), 'font-size', '20px'); // The first <p> element on the page will have a font-size of 20px
Shows all the elements specified.
Use the spread operator (...) and Array.forEach() to clear the display property for each element specified.
const show = (...el) => [...el].forEach(e => (e.style.display = '')); -
show(document.querySelectorAll('img')); // Shows all <img> elements on the page +
show(...document.querySelectorAll('img')); // Shows all <img> elements on the page
Toggle a class for an element.
Use element.classList.toggle() to toggle the specified class for the element.
const toggleClass = (el, className) => el.classList.toggle(className);
toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore
Generates a UUID in a browser.
Use crypto API to generate a UUID, compliant with RFC4122 version 4.
const UUIDGeneratorBrowser = () =>