2
3 Comments

Tips for writing more concise/Ruby-like vanilla Javascript?

I recently implemented Stimulus JS in our app and it's opened my eyes to some really nice, concise, snappy Javascript methods/operators that I wasn't using before. Such as:
element.classList.toggle('info-notice')
element.hidden = true
elements.forEach( x => { console.log(x.id) } )

Whilst I adore Ruby and am probably moving more towards live-updating server-rendered HTML (i.e. Hotwire) for our main app. We run a script on customers stores which is vanilla JS. I'd love to hear any suggestions on tight modern vanilla JS. Like the methods, patterns I mentioned above.

Thanks,
Oli

P.S. oh and am I right in thinking there isn't a less verbose version of document.getElementById('element') or document.querySelector('element')? It just seems super long-winded for such a common line.

  1. 3

    You can create a function to get elements -
    const getElement = (selection) => { const element = document.querySelector(selection); if (element) return element; throw new Error("no element selected"); };

    Then use it whenever required by calling it with the element name being the argument.
    getElement('.element')
    This shortens it significantly.

    Do let me know your thoughts on this approach.

    1. 1

      That looks great! I’ll be stealing that for sure 👌
      I’m not at a computer at the moment to play around with it, but I might tweak it to return null instead of an error. Just so I can use it in a truthy way too

  2. 2

    This comment was deleted 2 years ago.

    1. 1

      That’s lovely. Super compact. Thanks for the tip

Trending on Indie Hackers
Reaching $100k MRR Organically in 12 months 29 comments 87.7% of entrepreneurs struggle with at least one mental health issue 14 comments Passed $7k 💵 in a month with my boring directory of job boards 13 comments How to Secure #1 on Product Hunt: DO’s and DON'Ts / Experience from PitchBob – AI Pitch Deck Generator & Founders Co-Pilot 11 comments Worst Hire - my lessons 11 comments Competing with a substitute? 📌 Here are 4 ad examples you can use [from TOP to BOTTOM of funnel] 10 comments