I normally use document.getElementById('id').style.display = 'none'
to hide a single div via Javascript. Is there a similarly simple way to hide all elements belonging to the same class?
I need a plain Javascript solution that does not use jQuery.
Apparently SO wants me to edit this to clarify that it is not a question about modifying strings. It's not.
Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”.
Using Css style we can hide or show HTML elements in javascript. Css provides properties such as block and none to hide/show the HTML elements.
In the absence of jQuery, I would use something like this:
<script> var divsToHide = document.getElementsByClassName("classname"); //divsToHide is an array for(var i = 0; i < divsToHide.length; i++){ divsToHide[i].style.visibility = "hidden"; // or divsToHide[i].style.display = "none"; // depending on what you're doing } <script>
This is taken from this SO question: Hide div by class id, however seeing that you're asking for "old-school" JS solution, I believe that getElementsByClassName is only supported by modern browsers
There are many ways to hide all elements which has certain class in javascript one way is to using for loop but here i want to show you other ways to doing it.
1.forEach and querySelectorAll('.classname')
document.querySelectorAll('.classname').forEach(function(el) { el.style.display = 'none'; });
2.for...of with getElementsByClassName
for (let element of document.getElementsByClassName("classname")){ element.style.display="none"; }
3.Array.protoype.forEach getElementsByClassName
Array.prototype.forEach.call(document.getElementsByClassName("classname"), function(el) { el.style.display = 'none'; });
4.[ ].forEach and getElementsByClassName
[].forEach.call(document.getElementsByClassName("classname"), function (el) { el.style.display = 'none'; });
i have shown some of the possible ways, there are also more ways to do it, but from above list you can Pick whichever suits and easy for you.
Note: all above methods are supported in modern browsers but may be some of them will not work in old age browsers like internet explorer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With