Is there a way of having a NodeList of the HTML tags in Mithril? I need to get the width of the blocks. Something like that on vanilla js:
const blocks = Array.from(document.querySelectorAll('.blocks'));
const styles = blocks
.map((item) => item.getBoundingClientRect())
.map((item) => item.width);
const widthOfTheBlocks = styles.reduce((acc, curr) => acc + curr, 0) + 'px';
With typical DOM scripting, the DOM elements are pre-existing, and you would need to make sure they had identifiable selector (in this case the
blocksclass), and then elsewhere use that selector to get a Javascript reference to them, withdocument.querySelectorAll.But with Mithril, you're declaring and referencing the DOM elements in the same place, so you don't need either of these methods: instead you attach a lifecycle method on the appropriate node and save the reference to a local variable.
The lifecycle methods expose a
vnodeargument representing the virtual DOM entity: this contains adomproperty which exposes the rendered DOM element.The essential mechanism to save a reference inside a component is as follows:
Below, I've written a little sandbox demo that uses your width calculation script in a slightly more complex scenario: Here there's a variable number of blocks, which are added to and removed over time; we declare a
Setto store them, and for each item we declare anoncreatemethod toaddit to the set, and anonremovetodeleteit. I've used destructuring to extract thedomreference straight from the methods; later, we use a slightly tweaked version of your width accumulation code, using the 2nd argument ofArray.fromto extract thewidth.