Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<html>
<head>
<style type="text/css">
#main { padding: 100px; border: 2px solid pink; }
.blue { background-color: blue; }
</style>
</head>
<body>
<div id="main">Lorem ipsum dolor!</div>
<script type="text/javascript">
function $(selector) {
let selectorType = selector.split('').shift(); // grab the # or . from the selector
let selectorName = selector.substr(1); // grab the ID or class name from the selector
let DOMElement = selectDOMElement(); // select the DOM element
function selectDOMElement() {
if (selectorType === '#') {
return document.getElementById(selectorName);
} else {
return document.querySelectorAll(selectorName);
}
}
return {
addClass(className) {
DOMElement.classList.add(className);
},
removeClass(className) {
DOMElement.classList.remove(className);
},
hasClass(className) {
return DOMElement.classList.contains(className);
},
toggleClass(className) {
if (this.hasClass(className)) {
this.removeClass(className);
} else {
this.addClass(className);
}
}
}
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.