Hacker News new | ask | show | jobs
by tored 968 days ago
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.
1 comments

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.