Skip to content

Instantly share code, notes, and snippets.

@david-j-davis
Last active April 5, 2019 17:00
Show Gist options
  • Save david-j-davis/b51dccd5fb2aedc9c3c66d62dbc7f0c9 to your computer and use it in GitHub Desktop.
Save david-j-davis/b51dccd5fb2aedc9c3c66d62dbc7f0c9 to your computer and use it in GitHub Desktop.
ES6 class for a roll-your-own jQuery

Roll your own lightweight, build-what-you-need jQuery with an ES6 Class.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="update-me">Change me</div>
</body>
</html>
// construct a jQuery like class that can chain a jquery like css method and text method:
class jQuery {
constructor(selector) {
this.domElement = document.querySelectorAll(selector);
}
css(updates) {
for (let element of this.domElement) {
for (let [key, value] of Object.entries(updates)) {
element.style[key] = value
}
}
return this
}
text(update) {
for (let element of this.domElement) {
element.innerText = update
}
return this
}
}
// Dollar sign function with class instantiation
const $ = (selector) => {
const element = new jQuery(selector)
return element
}
// Then use it
$('.update-me').css({
'color': 'red',
'textTransform': 'uppercase'
}).text('Problem solved!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment