4 ms·
Instead of importing dsq you can do this const $ = document.querySelector.bind(document); const $$ = document.querySelectorAll.bind(document);
by bambax 3y ago
Instead of importing dsq you can do this
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
- mg 3y agoThat's what I did before I put those lines (and some more) into dqs.js
- throw555chip 3y agoThat's a neat shortcut, I prefer vanilla JS too.
- gmiller123456 3y agoThat's pretty much what that include file does, but with "dqs" rather than "$". I'm not a fan of using the $ as it might confuse others that you're using JQuery.
- bambax 3y agoWouldn't that be a feature? ;-)
- chrismorgan 3y ago$ is what I would expect and prefer, because it’s what I’ve been using in my browser dev tools for over fifteen years (ah, Firebug; fond reminiscences). If your document doesn’t use the names, you’ll get implementations roughly equivalent to these: function $(selector, element = document) { return element.querySelector(selector); } function $$(selector, element = document) { return Array.from(element.querySelectorAll(selector)); } Reference on more magic available in the console (there’s a lot of good stuff): • https://firefox-source-docs.mozilla.org/devtools-user/web_console/helpers/index.html https://firefox-source-docs.mozilla.org/devtools-user/web_co... (I think “:help” is my new favourite: opens that URL, which is not particularly discoverable) • https://developer.chrome.com/docs/devtools/console/utilities/ https://developer.chrome.com/docs/devtools/console/utilities...
- xeckr 3y agoOr const $ = (query) => document.querySelector(query); const $$ = (query) => document.querySelectorAll(query); (How do I write monospace on HN?)
- chrismorgan 3y ago> (How do I write monospace on HN?) Two-space indentation.
- xeckr 3y agoThank you
- bambax 3y ago> How do I write monospace on HN? Line that start with four spaces like this
- crtasm 3y agoIs there a way to make this also work as a function? e.g. myTable.$$('tr').foreach()
- mg 3y agoimport {qsA} from './dqs.js'; rows = qsA(myTable, 'tr');
- crtasm 3y agoThanks but the point is being able to chain it: myTable.qsA('tr') TypeError: myTable.qsA is not a function
- mg 3y agoWell, since html elements already have a querySelectorAll function, you could just assign it to a new method "qsA": HTMLElement.prototype.qsA = HTMLElement.prototype.querySelectorAll; Now myTable.qsA('tr') will work. You can try it right here on the HN page in the browser console: HTMLElement.prototype.qsA = HTMLElement.prototype.querySelectorAll; document.querySelector('#hnmain').qsA('tr'); Why do you prefer chaining?