Mithril.js: Nested selectors

m.nest('ul > li', 'Item') can be achieved with reduceRight().

m.nest = (selector, ...args) => {
const tags = selector.split('>')
const innermost = m(tags.pop().trim(), ...args)
return tags.reduceRight((child, tag) => m(tag.trim(), child), innermost)

// Usage:
m.nest(' > > a[target=_blank]', { href }, 'Link')

// The same as:
m('', m('', m('a[target=_blank]', { href }, 'Link')))

Test the code on


  • cleaner
  • clearer
  • cooler.


Original code on GitHub, by fuzetsu (Daniel Loomer). Variables renamed on this page for clarity.

Earlier version on Mithril's Gitter room, also by fuzetsu. Here the array is looped twice (map() + reduceRight()), whereas in the newer version (on this page) there's only one loop (reduceRight()).