views:

106

answers:

2

I've been at this for a while and I can't seem to crack it.. I have some javascript trying to hide sibling divs, besides the one that is passed through the function. Here's the html:

<div id = "chat_content">
 <div id = "chat_content_1">This is div one</div>
 <div id = "chat_content_2">This is div two</div>
 <div id = "chat_content_3">This is div three</div>
</div>

And here's the javascript:

    function showGroup(id)
 {
  // show the the div that was clicked 
  var e = document.getElementById(id);
  e.style.display = 'block';

        // hide the others divs under the same parent
  var children = e.parentNode.childNodes;
  for (var i = 0; i < children.length; i++)
  {
   if (children[i] != e)
   {
    children[i].style.display = 'none';
   }
  };
 }

thanks! and happy holidays :)

A: 

Consider using jQuery. Makes life easier. Check it out here

$("div#chat_content").siblings().css("display", "none");
gmcalab
thanks man. also it should be siblings()!
Matt
A: 

Is there any reason you're not using previousSibling or nextSibling? Your code should work in theory, but since it apparently doesn't (have you checked your error console?), try the following which works using a sort of iterator idea rather than an array loop:

// hide the others divs under the same parent
var child = e.parentnode.firstChild;

do
  {
    if (child != e)
      {
        child.style.display = 'none';
      }
    child = child.nextSibling;
  }
while (child.nextSibling != null);

I second the recommendation for using something like jQuery by the way. It does make things easier.

Dustin
hmm, it says child.style is undefined. I'll give jquery a shot, but do you have any ideas why this won't work?Thanks!
Matt
I'm not sure what the problem is. It should work, just like your code. Maybe there are no siblings or you're targeting the wrong element. Or maybe you had nonworking code and now the page isn't being updated because of caching?
Dustin