TWFPSP TWFPSP - 2 years ago 80
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 Source

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){

  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)



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download