20 January 2024

To achieve a show/hide functionality in vanilla JavaScript equivalent to jQuery's show() and hide() functions, you can utilize CSS classes or inline styles. In the example provided, a CSS class named "hidden" is used to set the initial state of the element to be hidden (display: none). The JavaScript code then toggles the visibility by adding or removing this class based on button clicks. The classList property is employed for manipulating classes, making it easy to manage the element's styling. Alternatively, you could directly manipulate the style property of the element to set the display property to "none" or "block" based on the desired visibility state. Both approaches provide a clean and efficient way to implement show/hide functionality without relying on jQuery.

Source code viewer
  1. // jQuery
  2. $('.class-to-show-and-hide').hide();
  3. $('.class-to-show-and-hide').show();
  4.  
  5. // Vanilla JavaScript using class.
  6. document.querySelectorAll('.class-to-show-and-hide').forEach(elementToToggle => {
  7. elementToToggle.classList.add('hidden');
  8. });
  9. document.querySelectorAll('.class-to-show-and-hide').forEach(elementToToggle => {
  10. elementToToggle.classList.remove('hidden');
  11. });
  12.  
  13. // Vanilla JavaScript using css styles.
  14. document.querySelectorAll('.class-to-show-and-hide').forEach(elementToToggle => {
  15. elementToToggle.style.display = 'none';
  16. });
  17. document.querySelectorAll('.class-to-show-and-hide').forEach(elementToToggle => {
  18. elementToToggle.style.display = '';
  19. });
Programming Language: ECMAScript