Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Mar 2011
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    getElementsByTag name problem?

    I have never used this object before and don't know a whole lot about javascript or DOM. I am trying to create a select menu so that when you click an option it turns the display attribute of the coorosponding div to just "" from the initial "none". This works fine just by grabbing the right ID.

    I also want to hide all other divs, even if they were previsously selected by mistake, so I thought I could use the get elements by tage name object to grab all the divs and then edit their display to "none". Maybe this is completely the wrong way to go about what I want to do, because eventually there will have to be forms nested within these divs. Any help would be appreciated, with the code or the method. Here is the function I have so far. nursing is the option it should display. I tried calling the length of my array and it came up correctly as 2, idk if that helps.

    Code:
    <script type="text/javascript">
    function nursing()
    {
    y= "nursing"
    divs = document.getElementsByTagName("div");
    
    if (document.getElementById(y).style.display="none")
    {
    document.getElementById(y).style.display="";
    }
    
    for (x in divs)
    {
    if(divs.Id!=y)
    {
    divs.style.display="none";
    }
    }
    }

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,553
    Thanks
    78
    Thanked 4,382 Times in 4,347 Posts
    This is wrong:
    Code:
       if(divs.Id!=y)
    The property is id, not Id. JavaScript is case sensitive.

    Also, the elements collection can't be iterated via the for...in syntax.

    Also this line
    Code:
        divs.style.display="none";
    is completely wrong. It is attempting to apply the style to the entire collection of <div>s.

    So:
    Code:
        for (var x = 0; x < divs.length; ++x )
        {
            if ( divs[x].id != y ) divs[x].style.display = "none";
        }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •