Last active
September 6, 2019 01:41
-
-
Save geotrev/3f858477ab3c252a24fc676ca1294477 to your computer and use it in GitHub Desktop.
Simple DOM manipulator utility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const dom = { | |
// Attribute manipulation | |
getAttr: (element, attr) => element.getAttribute(attr), | |
setAttr: (element, attr, value) => element.setAttribute(attr, value), | |
removeAttr: (element, attr) => element.removeAttribute(attr), | |
toggleAttr: (element, attr, forceCondition) => element.toggleAttribute(attr, forceCondition), | |
hasAttr: (element, attr) => element.hasAttribute(attr), | |
// Element selection | |
find: (selector, parent = document) => parent.querySelector(selector), | |
findAll: (selector, parent = document) => [...parent.querySelectorAll(selector)], | |
// CSS manipulation | |
css: (element, property, value) => { | |
if (typeof value === "string" || value === null) { | |
return (element.style[property] = value) | |
} | |
return element.style[property] | |
}, | |
// Class manipulation | |
addClass: (element, ...classes) => element.classList.add(...classes), | |
removeClass: (element, ...classes) => element.classList.remove(...classes), | |
toggleClass: (element, className, forceCondition) => element.classList.toggle(className, forceCondition), | |
replaceClass: (element, oldClass, newClass) => element.classList.replace(oldClass, newClass), | |
hasClass: (element, ...classes) => classes.filter(givenClassName => element.classList.contains(givenClassName)).length > 0, | |
// Element height and width getters | |
getHeight: element => Math.ceil(element.getBoundingClientRect().height), | |
getWidth: element => Math.ceil(element.getBoundingClientRect().width), | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment