Skip to content

Instantly share code, notes, and snippets.

@annibal
Last active November 25, 2026 05:55
Show Gist options
  • Select an option

  • Save annibal/b136c8f7cc252545bddbc3b7729b625b to your computer and use it in GitHub Desktop.

Select an option

Save annibal/b136c8f7cc252545bddbc3b7729b625b to your computer and use it in GitHub Desktop.
Generate HTML and Query elements with the H() and Q() functions

H() & Q()

Easily create and manipulate HTML with H() and Q()! [View H_and_Q .js]

  • H("<h1>Str</h1>") - Parse HTML from string;
  • Q(".active") - Query HTML in HTML;
  • NoneOneAll(elm) - Let T be the type of elm, give me either null, T or T[], always;
// import n2blHQ from "n2blHQ" // or import FactoryHQ // or <script src=""></script> // or whatever you prefer // TODO: put raw script gist URL in this comment
const { H, Q } = n2blHQ();

// make the layout from Html
const layoutElm = H(`<div class="some__thing"><h1>Title</h1><p>Subtitle</p><div class="some-thing--body">...</div></div>`);

// fetch some data
const actions = await fetch("...");

// map data to elements
const elmsActions = H(actions.map(a => `<a href="${a.url}">${a.label}</a>`));

// Query the reference to the "slot" within the layout descendant elements
const elmH1 = Q("h1", layoutElm);

// insert data-elements into slot
elmsActions.forEach(elm => elmH1.prepend(elm));

// all done, do something with this
Q("body > #main-content .things_container).appendChild(layoutElm);

Files in this GIST

  • H_and_Q.js - Latest, prettiest and best version of this lib. Requires const { H, Q } = n2blHQ();

  • HTMLandQueryUtil.js - Legacy version of H() and Q() "lib", probably still in use by some codepen i made in the past, kept it so they don't break. H(), Q(), NoneOneAll() and helper stuff are declared straight away in this file;

  • examples_HTMLandQueryUtil.js - Silly examples of how to use H() and Q().

(()=>{const e=t=>[()=>null,e=>e[0],e=>Array.from(e)][(e=>+!!e+(e>1))(t?.length)](t);let t=[];try{const e=document;if(!e)throw new Error("[H()+Q()]: Global variable Document (<html />) is not accessible");const n=document.body;if(!e)throw new Error("[H()+Q()]: Global reference to Body (<body />) is not accessible");t=[n]}catch(e){try{console.error(e)}catch(e){}}const n=Object.freeze({HTML:"text/html",XML_OLD:"text/xml",XML:"application/xml",XHTML:"application/xhtml+xml",XML_SVG:"image/svg+xml"});Object.assign(globalThis,{NoneOneAll:e,H:(t,o=n.HTML)=>{let r=o;o&&Object.values(n).includes(o)||(r=n.HTML);const l=new DOMParser().parseFromString(t,r);try{return e(l.body.children)}catch(e){return console.error("[H()+Q()]: Error on H() at NoneOneAll"),console.error(e),null}},Q:(n,o=t)=>e((Array.isArray(o)?o:[o]).map(t=>t&&"function"==typeof t.querySelectorAll?e(t.querySelectorAll(n)):null).flat().filter(Boolean))})})();
// Example:
html_and_query_example_1 = () => {
// will find the "font-sans" elements, direct children of "block", that are the 2nd of the children element
const selectorStr = ".block > .font-sans:nth-child(2)";
// will use this as the HTML DOM, render it, return the HTML Objects, and pass it to the Q.
const htmlStr = `<div class="relative w-2xl">
<img src="https://is.gd/sMACTk" />
<section class="h-32 w-32 bg-indigo block">
<h1>title</h1>
<code class="px-1 py-1 font-sans">H(); Q()</code>
</section>
</div>
<div class="alert block">
<i class="fa fa-warning" />
<span> Lorem Ipsum! </span>
</div>
<div class="px-4 py-4 block">
<p class="font-sans"> one </p> | <p class="font-sans"> two </p> | <p class="font-sans"> three </p>
</div>`;
return Q(selectorStr, H(htmlStr));
// should find two elements: <code> and the <p>two</p>
}
const html_and_query_example_2 = (() => {
const content = H("<div class=content>"+
"<p>quia dolor sit, amet, consectetur, adipisci velit</p>"+
"<p>sed quia non numquam eius modi tempora incidunt,</p>"+
"<p>ut labore et dolore magnam aliquam quaerat voluptatem.</p>"+
"</div>");
const card = H("<section>"+
"<header><h1>Dolorem Ipsum</h1></header>"+
content.outerHTML,
"</section>");
const text = Q(".content", elm).innerText;
const title = Q(".header", elm).innerText;
const footer = H("<footer><small>"+
`<code>${new Date().toLocaleDateString()}</code>`+
"</small></footer>");
card.appendChild(footer);
return card;
})
(() => {
const NoneOneAll = (predicate) => [
() => null,
(p) => p[0],
(p) => Array.from(p),
][((len) => +!!len + (len > 1))(predicate?.length)](predicate);
let defaultRootElm = [];
try {
if (!document) throw new Error("[H()+Q()]: Global variable Document (<html />) is not accessible");
if (!document.body) throw new Error("[H()+Q()]: Global reference to Body (<body />) is not accessible");
defaultRootElm = [document.body];
} catch (err) {
try { console.error(err); } catch {}
}
const MIME_TYPES = Object.freeze({
HTML: "text/html",
XML_OLD: "text/xml",
XML: "application/xml",
XHTML: "application/xhtml+xml",
XML_SVG: "image/svg+xml",
});
const H = (str, mime = MIME_TYPES.HTML) => {
const validMime = Object.values(MIME_TYPES).includes(mime) ? mime : MIME_TYPES.HTML;
const parsedRoot = new DOMParser().parseFromString(str, validMime);
try {
return NoneOneAll(parsedRoot.body.children);
} catch (err) {
console.error("[H()+Q()]: Error on H() at NoneOneAll", err);
return null;
}
};
const Q = (query, rootElm = defaultRootElm) => NoneOneAll(
(Array.isArray(rootElm) ? rootElm : [rootElm])
.map((el) => (typeof el?.querySelectorAll === "function" ? NoneOneAll(el.querySelectorAll(query)) : null))
.flat()
.filter(Boolean)
);
Object.assign(globalThis, { NoneOneAll, H, Q });
})();
// Parse an string into a DOM element tree
const H = (str, mime) => {
let validMime = mime;
if (!mime || !Object.values(H_MIME_TYPES).includes(mime)) {
validMime = H_MIME_TYPES.HTML;
}
const parsedRoot = new DOMParser().parseFromString(str, validMime);
try {
return NoneOneAll(parsedRoot.body.children);
} catch (e) {}
return parsedRoot;
}
// Find elements from a given DOM tree, by default document.body
const Q = (query, rootElm = document.body) => NoneOneAll(
(Array.isArray(rootElm)
? rootElm
: [rootElm]
).map(
relm => (!relm || typeof relm.querySelectorAll !== "function")
? null
: NoneOneAll( relm.querySelectorAll(query) )
).flat().filter(Boolean)
)
// Normalize a value into null, a single thing, or an actual array
// const NoneOneAll = (items) => (!items || items?.length < 1)
// ? null
// : (items.length == 1
// ? items[0]
// : Array.from(items)
// )
// ;
// faster version:
const NoneOneAll = (children) => (
(
[
() => null,
children => children[0],
children => Array.from(children)
][
(
(len) => ( +!!len ) + ( len > 1 )
)(children?.length)
]
)(children)
);
const H_MIME_TYPES = Object.freeze({
HTML: "text/html",
XML_OLD: "text/xml",
XML: "application/xml",
XHTML: "application/xhtml+xml",
XML_SVG: "image/svg+xml",
});
function n2blHQ() {
// TODO: configuration (restrict to init?)
// TODO: error strategy
// TODO: third cool single letter function
// TODO: addEventListener wrap, maybe?
// #region NoneOneAll
/**
* Normalize a value into either null,
an array, or a single thing,
based on whether it coalesces to
empty, many, or something else.
* @param {T} predicate - Well this
could be of a massive plethora
of types.
* @returns {null|T|T[]} - This may
still be one in a (countable)
infinite pool of types but now
it's known that it may ALSO be
null, or ALSO be a list of any
combination of that
aforementioned variety of things.
*/
const NoneOneAll = (predicate) => (
(
[
() => null,
predicate => predicate[0],
predicate => Array.from(predicate)
][
(
(len) => ( +!!len ) + ( len > 1 )
)(predicate?.length)
]
)(predicate)
);
// #endregion NoneOneAll
// ===================================================
// #region Definitions
let defaultRootElm = [];
try {
const doc = document;
if (!doc) { throw new Error("[H()+Q()]: Global variable Document (<html />) is not accessible"); }
const body = document.body;
if (!doc) { throw new Error("[H()+Q()]: Global reference to Body (<body />) is not accessible"); }
defaultRootElm = [body];
} catch(err) {
try { console.error(err); }
catch (e2) { /* cannot console log, so end program in confusion */ }
}
const H_MIME_TYPES = Object.freeze({
HTML: "text/html",
XML_OLD: "text/xml",
XML: "application/xml",
XHTML: "application/xhtml+xml",
XML_SVG: "image/svg+xml",
});
// #endregion Definitions
// ===================================================
// #region HTML_Generate
/**
* Parse an string into a DOM element tree.
Returns either a single HMTLElement,
or an array of HTMLElements,
or null,
depending on the input string.
* H() will only return the HTMLElements,
only what `body.children` returns,
it doesn't parse stuff like text nodes.
* If you really want these, wrap them in a single root
element in the string, and access via `childNodes`,
for example: H(" RE text1 text2 /RE ").childNodes, or
`H("&lt;div&gt; my &lt;br /&gt; text &lt;br /&gt; nodes &lt;br /&gt; nice &lt;/div&gt;").childNodes`
*
* @example
* // returns {HTMLDivElement}
* H("&lt;div&gt;&lt;/div&gt;");
*
* @example
* // returns {[HTMLSpanElement, HTMLAnchorElement]}
* H(&lt;span class="highlight-arrow" &gt;→&lt;/span&gt;"&lt;a href="https://nibal.art"&gt;My Website&lt;/a&gt;);
*
* @example
* // returns {null}
* H("&lt;i am='your father! /&gt;")
*
* @example
* // returns {HTMLUnknownElement}
* H("i <am> your father!")
*
* @param {string} str - An document object tree description
* @param {string=} [mime="text/html"] - How to parse this string.
The default, "text/html" is loose,
while all others are pretty much
the same, but stricter.
* @returns {(null|Document|Document[])}
*/
function HTML_Generate(str, mime = H_MIME_TYPES.HTML) {
// const H = (str, mime = H_MIME_TYPES.HTML) => {
let validMime = mime;
if (!mime || !Object.values(H_MIME_TYPES).includes(mime)) {
validMime = H_MIME_TYPES.HTML;
}
const parsedRoot = new DOMParser().parseFromString(str, validMime);
try {
return NoneOneAll(parsedRoot.body.children);
} catch (err) {
console.error("[H()+Q()]: Error on H() at NoneOneAll");
console.error(err);
return null;
}
return parsedRoot;
}
// #endregion HTML_Generate
// ===================================================
// #region QueryElms2
/**
* Find elements from a (one or many) given DOM tree root(s) (by default document.body),
and a given selector string (see "CSS selector"), returning null
if nothing was found, one if found exactly one match, or an array
if there was two or more matches.
This function will try to instantiate `document.body` on it's first
run, to use as the default root element. If you're running this
code in an non-browser environment, it will default to `[]`, which
means it will never find a match unless supplied with a proper root.
*
* @param {string} query - The selector string that finds the desired element(s).
* @param {HTMLElement=|HTMLElement[]=} [rootElm=[document.body]] - from which point in
the document model structure to begin the search from.
Defaults to <body /> if your js environment has that,
otherwise defaults to [].
* @returns {null|HTMLElement|HTMLElement[]}
*/
function QueryElementsInElement(query, rootElm = defaultRootElm) {
return NoneOneAll(
// const Q = (query, rootElm = defaultRootElm) => NoneOneAll(
(Array.isArray(rootElm)
? rootElm
: [rootElm]
).map(
relm => (!relm || typeof relm.querySelectorAll !== "function")
? null
: NoneOneAll( relm.querySelectorAll(query) )
).flat().filter(Boolean)
)
}
// #endregion QueryElms2
// ===================================================
// #region Return
return {
Q: QueryElementsInElement,
H: HTML_Generate,
H_MIME_TYPES
}
// #endregion Return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment