treehouse : what would you like to learn today?
Web Design Web Development iOS Development

document.getElementById - How to make it get more than one id

  • Hey guys, I'm not sure if that's possible but I 'm trying to somehow make this code to get more than on element id instead of just one Id. Here's what I have:


    onClick="document.getElementById('b1').style.display='none';"


    Anyone knows how to do this?
    Maybe any alternative ways?
  • There are a lot of ways to do this, but the easiest of all would be to use document.getElementsByClassName instead of ID
    That's if it's possible to add classes in your scenario
  • I tried different ones like .getElementsByClassName .getElementsByName but it only works for "id" (for one element).


    The thing is I have the individual id's for separate images in a table.
    And when clicked on a link(s) using the code above I want to make multiple elements disappear/appear.

    I used some complicated javascript code before but it only allowed me to make one link but hide multiple elements.

    Any other suggestions? But thanks for the help anyway
  • I was thinking of a for loop to do it but I hit a brick wall
    http://jsfiddle.net/48ypF/1/

    Can anybody see where I went wrong?
  • <script>
    function hideDivs() {
    var x, divArray = ["id1", "id3"];
    for (x in divArray) {
    if (x) {
    document.getElementById(divArray[x]).style.display = 'none';
    }
    }
    }
    </script>


    <div id=id1>Hello 1</div>
    <div id=id2>Hello 2</div>
    <div id=id3>Hello 3</div>


    <button onClick="hideDivs();">Hide 1 and 3</button>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
    Figured it out :)
  • Thank you so much! This works great, but there is only one little problem, how do I apply this to hide id1 and id3 using one button and then hide id2 using another button?

    I'm not that good with javascript.

    I hope I'm not taking too much of your time.
  • <script>
    function hideDivs(divArray) {
    var x;
    for (x in divArray) {
    if (x) {
    document.getElementById(divArray[x]).style.display = 'none';
    }
    }
    }
    </script>
    <div id=id1>Hello 1</div>
    <div id=id2>Hello 2</div>
    <div id=id3>Hello 3</div>
    <button onClick="divArray = ['id1', 'id3'], hideDivs(divArray);">Hide 1 and 3</button>
    <button onClick="divArray = ['id1', 'id2'], hideDivs(divArray);">Hide 1 and 2</button>
    <button onClick="divArray = ['id2', 'id3'], hideDivs(divArray);">Hide 2 and 3</button>​


    slight rework, not sure if its the best way, but it works :D