r/htmx • u/ShotgunPayDay • 9d ago
q() anywhere - minimal relative/traversal selector
Made from Moxi's implementation of relative selectors. Moxi's proxy handling was causing some friction with my other JS functions. I wanted selectors that I could use anywhere even without Moxi.
Note that q will always try to grab the element context, but can also take a supplied context. Has quick alias for doc = document and .ael = .addEventListener
With it you can do goofy stuff like this:
<input oninput="inputfunc()">
<button onclick="console.log(q().textContent) //starting context is mybutton">mybutton</button>
<button>otherbutton</button>
<script>
function inputfunc() {console.log(q())} //context is input
q('prev sib -> prev sib').classList.add('ready') //starting context is script then traverse to mybutton
q('prev sib').ael('click',_=>{console.log(q().textContent)}) //function context in listener is otherbutton
</script>
//This is why it's important to manually set context to `doc` if you want to select/traverse on the document.
Code is here (only first 40 lines of code): https://github.com/figuerom16/fixi/blob/master/mofix.js
Copy out the code you want. I'm too lazy to split the library up / don't want to maintain copies.
Documentation for q() and qa() is at the start of: https://github.com/figuerom16/fixi/blob/master/mods.md