Hiding all elements with the same class name?

vanilla javascript

function toggle(className, displayState){
    var elements = document.getElementsByClassName(className)

    for (var i = 0; i < elements.length; i++){
        elements[i].style.display = displayState;
    }
}

toggle('float_form', 'block'); // Shows
toggle('float_form', 'none'); // hides

jQuery:

$('.float_form').show(); // Shows
$('.float_form').hide(); // hides

If you're looking into jQuery, then it's good to know that you can use a class selector inside the parameters of $ and call the method .hide().

$('.myClass').hide(); // all elements with the class myClass will hide.

But if it's a toggle you're looking for, use .toggle();

But here's my take on a good toggle without using jQuery:

function toggle( selector ) {
  var nodes = document.querySelectorAll( selector ),
      node,
      styleProperty = function(a, b) {
        return window.getComputedStyle ? window.getComputedStyle(a).getPropertyValue(b) : a.currentStyle[b];
      };

  [].forEach.call(nodes, function( a, b ) {
    node = a;

    node.style.display = styleProperty(node, 'display') === 'block' ? 'none' : 'block';
  });

}

toggle( '.myClass' );

Demo here (Click "Render" to run): http://jsbin.com/ofusad/2/edit#javascript,html

Tags:

Javascript