开发者

javascript, can't retrieve sibling nodes

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开发者_StackOverflow 
        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 :)


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

$("div#chat_content").siblings().css("display", "none");


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜