Home > Net >  Is it possible to loop through multiple ID'S to change an attribute
Is it possible to loop through multiple ID'S to change an attribute

Time:06-12

<script type="text/javascript">
    var packetStorageNum = 0;

    function increase_stored(){
        packetStorageNum  ;
        if(packetStorageNum>6){
            packetStorageNum = 6
        }
    }
    function decrease_stored(){
        packetStorageNum--;
        if(packetStorageNum<0){
            packetStorageNum = 0
        }
    }
    function run()
    {
        for(let i = 1;i<packetStorageNum 1;i  ){
            document.getElementById('i').style.display='block';
        }
        
    }
</script>
<body>
    <div >
        <p>number of packets in storage:</p>
        <div >
            <input type="button" onClick="increase_stored()" value="Increase"/>
            <input type="button" onClick="decrease_stored()" value="Decrease"/>
        </div>
        <input type="button" onClick="run()" value="Run"/>
    </div>

    <div>
        <div><img src="images/box.jfif" alt="" id="1" style="display:none ;"></div>
        <div><img src="images/box.jfif" alt="" id="2" style="display:none ;"></div>
        <div><img src="images/box.jfif" alt="" id="3" style="display:none ;"></div>
        <div><img src="images/box.jfif" alt="" id="4" style="display:none ;"></div>
        <div><img src="images/box.jfif" alt="" id="5" style="display:none ;"></div>
        <div><img src="images/box.jfif" alt="" id="6" style="display:none ;"></div>         
    </div>
</body>

The code is to 'turn on' certain images as the increase button is clicked and to hide them when its not. I gave the boxes id's of numbers and was trying to use a For loop to go through the numbers so when the value of boxes is say 5, box 1-5 will be visible.

CodePudding user response:

You need to use i as the variable - currently you're looking for an element with the id #i rather than #1, #2 etc.

document.getElementById(i.toString()).style.display = "block";
  • Related