I mean it could be optimized, but it's probably the wrong approach. Just have a class attached to the elements you want to hide, named appropriately, and then hide the elements with that class.
Extremely easy with jQuery, a bit more complex but still easy with vanilla JS.
And it would be more extendible when you need to change which are getting hidden when.
What does jQuery provide in that case? The $ selector? We've had querySelector and querySelectorAll in browsers for years now which does the same thing.
Right, you could set the class on all the elements at once with jQuery, while you would have to loop through the NodeList with querySelectorAll to set it.
Better than the code in the post definitely, it would work but the point is you don't have to know the ID of each element you want to update, you just apply a class in the html whenever you want to apply the functionality.
It ould be better to use an ID at times especially if it's just one element at one event, but here it is pretty clear they are trying to do it over a group of them.
Actually as I think about it, using a class in the HTML is pretty much doing as you suggested, it's just providing a way to get the array of elements
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/jso__, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.
For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.
/u/jso__, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.
It's a pretty large library, and modern vanilla JS can do everything jQuery does anyway, so it's mostly pointless.
That said, in case your project has some dependency where jQuery is required anyway, eg bootstrap (pre v5.0), the compact syntax that jQuery offers is pretty handy.
View all comments
49
u/LoyalEnvoy Aug 21 '21
i am learning JavaScript could you please show me how to optimize this? Thanks!