• WordPress for Business Websites
  • Polished Stone, LLC

Christopher Hess

About Life, Technology, and Entrepreneurship.

  • Email
  • Facebook
  • Linkedin
  • Twitter
  • WordPress for Business Websites
  • Polished Stone, LLC

Hide All Divs Except The Active One

February 21, 2008 by hesscj Leave a Comment

So in the past I’ve tried to come up with code so that when you click a link that “unhides” a div, that it closes the rest of them. Well today I was working on something where I needed that functionality and I thought I’d post it for all to use. I’m sure I’m not the first to come up with this, but here it is:

function show(id)

{
var divArray = document.getElementsByTagName(‘div’);
var div = document.getElementById(id);
for each (divItem in divArray)
{
if(divItem != div)
{
divItem.style.display=”none”;
}
else
{
divItem.style.display = “”;
}
}
}

So when you make a call to show() you pass the id of the div you would like to show. Show(‘one’); for instance would show the div where the id=”one” and would go through and hide the rest of the divs.
This code could be changed to use any type instead of just a div if desired.

EDIT: I found that in the array returned, the last element is the number of objects returned. If there were 3 divs, then it would be 3, if there were 4, then 4. You get the idea… One way to remove the problem of having the last item is putting an if statement around the if… else that already exists.
This could read: if(typeOf(divItem) == ‘object’)

Filed Under: Tech Tagged With: Code, Tips

February 21, 2008 by hesscj Leave a Comment

Logging In...

Profile cancel

Sign in with Twitter Sign in with Facebook
or

Not published

Recent Posts

  • Specialization vs. redundancy
  • “Dude, suckin’ at something is the first step to being sorta good at something.” —Jake, “Adventure Time” via @momentumdash
  • “If you want something big, it’s critical to make that initial choice to commit to a tangible and specific outcome.” — @ramit
  • A Flying Baseball Bat, a Dad’s Instinct and a Photograph
  • “We need to expect failure and plan what we’ll do when rejection comes. Every top performer does this.” — @ramit http://bit.ly/1TLUIGr

Archives

Categories

  • Business
  • Dashboards
  • General
  • Happiness
  • Moab
  • Productivity
  • Tech
  • Tweet
  • WordPress

© 2019 Christopher Hess