Skip to content
Advertisement

showing/hiding html elements with javascript

which option among the following is better or used as a standard way to show/hide the html elements

  1. changing element.style.display
  2. adding/removing a separate class called hide {display: none}
  3. any other standard way

PS: this JavaScript hide/show element question uses the first option mentioned( changes the style to block to show which may not be desired). I would like to know whether this method is used in most websites or the adding /removing a separate class or any other way

  1. A third way in the answers below https://stackoverflow.com/a/68983509/14478972

Advertisement

Answer

I prefer to toggle a class using DOMTokenList.toggle():

The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn’t exist it’s added and the function returns true.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement