TWFPSP TWFPSP - 7 months ago 17
Javascript Question

Hide/show elements using only Javascript without messing with DOM

Just wondering, is it possible to use only Javascript to hide/show elements without using "style" method? So I won't have to use any inline CSS in my HTML element. Or even, how does jQuery perform the hide/show event in its core?

Answer

You can do it by adding/removing a CSS class with both Javascript and Jquery.

Assuming this is the CSS class that gets added to the DOM element:

.hide { display: none}

Then you can use:

Javascript v1

function toggleClass(element, className){
  if (!element || !className){
    return;
  }

  var classString = element.className, nameIndex = classString.indexOf(className);
  if (nameIndex == -1) {
    classString += ' ' + className;
  }
  else {
    classString = classString.substr(0, nameIndex) + classString.substr(nameIndex+className.length);
  }
  element.className = classString;
}

Javascript v2 (classList.toggle() supported by most modern browsers)

document.getElementById('foo').classList.toggle('hide');

jQuery

$('#foo').toggleClass('hide');