Created
August 4, 2020 14:25
-
-
Save craigerskine/9d8cdfb3aceb74ff2cf5cc3349423157 to your computer and use it in GitHub Desktop.
ES6 - jQuery-like selector logic
This file contains hidden or 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
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<meta http-equiv="x-ua-compatible" content="ie=edge" /> | |
<title>ES6 - jQuery-like Selector + classList add/remove example</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet" /> | |
</head> | |
<body class="bg-gray-900 text-gray-600"> | |
<div class="p-4 w-screen h-screen flex"> | |
<!-- list items to manipulate --> | |
<ul class="m-auto w-full max-w-md"> | |
<li class="mb-1 p-2 bg-gray-800 rounded"></li> | |
<li class="mb-1 p-2 bg-gray-800 rounded" id="selected"></li> | |
<li class="mb-1 p-2 bg-gray-800 rounded"></li> | |
<li class="mb-1 p-2 bg-gray-800 rounded"></li> | |
</ul> | |
</div> | |
<script> | |
// selector function | |
window.$_ = function(selector, next) { | |
var selectors = document.querySelectorAll(selector); | |
[].forEach.call(selectors, next); | |
}; | |
// select all list items and insert html | |
$_('ul > li', function(e){ | |
e.innerHTML = 'Bar'; | |
}); | |
// select last list item and do stuff | |
$_('ul > li:last-child', function(e){ | |
e.insertAdjacentHTML('beforeend', ' <small class="ml-1 text-xs uppercase opacity-50">Last</small>'); | |
e.classList.remove(...['mb-1']); | |
}); | |
// select a specific element and do stuff | |
$_('#selected', function(e){ | |
e.innerHTML = 'Foo'; | |
e.classList.remove(...['bg-gray-800']); | |
e.classList.add(...['bg-red-600', 'text-red-200', 'transform', 'scale-105']); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment