Hacker News new | ask | show | jobs
by WorldMaker 969 days ago
Mostly off the top of my head:

    document.getElementById('some-form').getElementsByTagName('input').forEach(i => i.classList.add('error'))
It is a little more verbose but it isn't that much more cumbersome today.

That's also doing things "the right way" and not do-all selectors, but that option exists now, too:

    document.querySelectorAll('#some-form > input').forEach(i => i.classList.add('error'))
If you want to make it a little less verbose:

   const $ = document.querySelectorAll
   const addClass = (className) => (item) => item.classList.add(className)
   $('#some-form > input').forEach(addClass('error'))
2 comments

However getElementById() can return null, thus that entire statement can error. In the old days you had to sprinkle your code with if checks when using the DOM API.
If you are requiring that element to be there for your script to work then that error is exactly what you want. Defensive programming is great and all, but sometimes your assumptions have to meet the road anyway and script errors are a perfect way to signal something went wrong (because that's what they are for).

Of course now we have additional defensive programming tools like `?.` and `??` operators.

It depends, if the page is very dynamic the element may or may not be there.

Point is that the DOM API version of the initial jQuery snippet are not equivalent. $() statement does a bit more than that.

This becomes obvious if the requirement are a bit more complex than the example, perhaps we want to chain more expression on at the end, then the DOM API version becomes more convoluted.

Love the syntax in the last example, you should make it into a library!
Maybe that npm package could get as famous as leftpad.