Hide element by class in pure Javascript
For a quick hide for all elements with a specific class, use this snippet:
Replace .yourClass
with the class that you want to make invisible. This is an effective one-liner that immediately hides all elements with the respective class.
Diving into the methods
Now that we have a quick solution, let's discuss the nuances and go deeper into the methods of hiding elements in various environments and scenarios.
Display property
In some circumstances, you may want the elements not to occupy space after they are hidden. This would involve using the display
property:
HTMLCollections and for loop
If you're working with getElementsByClassName
, which gives you an HTMLCollection
, you can use a for loop to apply styles to each element:
ES6 support and for...of Loop
If you're in an ES6-friendly environment, the for...of
loop makes your code cleaner and more readable:
Everything's visible here — or is it?
Aside from display
, the visibility
property is another way to hide elements. This hides elements while still retaining their layout space:
Cross-compatibility considerations
Don't forget to consider the compatibility of your JavaScript amongst various environments:
- For older browsers or non-ES6 environments, be old school and use the good old
for
loop:
- In Objective-C WebView environments, vanilla JavaScript methods should prevail, despite the evaluation constraints.
Edge cases, caveats, and troubleshooting
In dynamic applications, new elements might spawn after your script has run. To prevent them from crashing your invisible party, use MutationObservers to watch for changes and apply styles as new elements join the fiesta.
Additionally, ensure that your selectors are not having a duel with any of JavaScript's reserved keywords or picking fights with other JavaScript frameworks, such as jQuery.
Optimizing your invisibility cloak
To make your invisibility act a crowd pleaser, consider these optimization tips:
- Cache your selectors if they are getting too popular in your code.
- Rally behind the classList to add a hidden class with predefined styles in your CSS. It might be faster than handling individual styles and it's certainly more self-explanatory to other developers.
Was this article helpful?