I've been using this for years: const $id = new Proxy({}, { // get element from cache, or from DOM get: (tgt, k, r) => (tgt[k] || ((r = document.getElementById(k)) && (tgt[k] = r))), // prevent programming errors set: () => $throw(`Attempt to overwrite id cache key!`) }); It's nice to be able to refer to elements by property name, so: Is reachable with: $id.thing And, since the underlying structure is just an object,…
Should that be `Object.create(null)` to avoid problems with ` `?
TinyJS – Shorten JavaScript QuerySelect with $ and $$
91–94 of 94 posts
Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$
#92``` const $ = (param) => { if (typeof param === "string" || param instanceof String) { const elm = document.querySelectorAll(param); return elm.length > 1 ? elm : document.querySelector(param); } else { return [param].length === 1 ? [param][0] : [param]; } }; ```
Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$
#93Earlier quoted context omitted.
I also put together a Proxy microlib a few years ago. I agree it's very powerful. You can use it like: $('.my-elements').className = 'Important'; $('.my-elements').style.color = 'Red'; $('.my-elements').classList.add('Another'); const $ = (() => { function listProxy(arr) { return new Proxy(arr, { set: (t, p, v, r) => { for(let x of t) { x[p] = v; } }, get: (t, p, r) => { if(t.length > 0 && t[0][p] instanceof Function…
I built a Proxy-based microlib for making fluent REST calls just on a lark a couple years ago. It was never anything production-ready, but it was so handy that I used it in all of my JS projects until I moved away from webdev. The API was basically: const api = new Proxy({route: baseRoute}, handler); // handler is the microlib's export const result = await api.get.some.route.invoke(); // GET {baseRoute}/some/route in…
`api.some.route.get()`
Re: TinyJS – Shorten JavaScript QuerySelect with $ and $$
#94Earlier quoted context omitted.
Generally, I would recommend avoiding directly setting the innerHTML property, since it's vulnerable to XSS and other injection attacks. If you do, make sure you HTML-escape each variable you interpolate. Here's a way to do that with a tagged template function (named it `htmlFragment` to make it super clear what it's for): // a couple of functions to help const sanitizeHTML = (unsafeStr) => { const div = document.cre…
Would you not just be able to do the following: const div = document.createElement('div'); const text = 'This is a dynamically generated paragraph'; div.insertAdjacentHTML("beforeend", ` Hello world ${text} `); document.body.append(...div.children); Edit, figured I'd add the docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/ins...
From the MDN page:
> When inserting HTML into a page by using insertAdjacentHTML(), be careful not to use user input that hasn't been escaped.