diff --git a/.gitignore b/.gitignore index 67045665d..a6b984db0 100644 --- a/.gitignore +++ b/.gitignore @@ -102,3 +102,4 @@ dist # TernJS port file .tern-port +.DS_Store diff --git a/blog_images/pineapple-at-work.jpg b/blog_images/pineapple-at-work.jpg new file mode 100644 index 000000000..8bf2d51d0 Binary files /dev/null and b/blog_images/pineapple-at-work.jpg differ diff --git a/blog_posts/javascript-query-selector-shorthand.md b/blog_posts/javascript-query-selector-shorthand.md new file mode 100644 index 000000000..1359f3a7f --- /dev/null +++ b/blog_posts/javascript-query-selector-shorthand.md @@ -0,0 +1,20 @@ +--- +title: "Tip: Create your own query selector shorthand" +type: tip +tags: javascript,browser +authors: chalarangelo +cover: blog_images/pineapple-at-work.jpg +excerpt: Ever wanted to create your own jquery-like query selector shorthand? Here's how! +--- + +Most of us are familiar with jquery and probably quite a few of us are familiar with the Chrome console's `$` and `$$` shorthands for query selectors. I recently figured out a way to replicate these shorthands in my code, using `Document.querySelector()`, `Document.querySelectorAll()` and `Function.prototype.bind()`. Here's how to do it, just make sure you don't mix them up with jquery if you are still using it: + +```js +const $ = document.querySelector.bind(document); +const $$ = document.querySelectorAll.bind(document); + +const mainContent = $('.main-content'); +const externalLinks = $('a[target="_blank"]'); +``` + +**Image credit:** [engin akyurt](https://unsplash.com/@enginakyurt?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)