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 3 of 3

Thread: for loop help

  1. #1
    New to the CF scene
    Join Date
    Nov 2012
    Posts
    8
    Thanks
    4
    Thanked 0 Times in 0 Posts

    for loop help

    I'm working on a random project that takes a lot of code so I'm trying to use javascript to make it easier.

    This is what I want to do.
    Code:
    else if(x.className=="change0") {
    x.className="change1";
    }
    else if(x.className=="change1") {
    x.className="change2";
    }
    else if(x.className=="change2") {
    x.className="change3";
    }
    
    |
    v
    |
    v
    |
    v
    
    else if(x.className=="change358") {
    x.className="change359";
    }
    I did a for loop for this.

    Code:
    <!DOCTYPE html>
    <html>
    <body onload="myFunction()">
    
    <p id="demo"></p>
    
    <script>
    function myFunction()
    {
    var x="";
    for (var i=0;i<359;i++)
      {
      x=x + "else if(x.className==&#38;#34;change" + i + "&#38;#34;) {<br>x.className=&#38;#34;change#&#38;#34;;<br>}<br>";
      }
    document.getElementById("demo").innerHTML=x;
    }
    </script>
    
    </body>
    </html>
    I can't get the first number to start at 0 while the other number starts at 1.

    Code:
    else if(x.className=="change0") {
    x.className="change1";
    }

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    Oh my, what a construct. Ever heard of variables holding numbers and string concatenation?

    The only thing you want to do is to count +1 for the class name of a certain DOM element? Which DOM element is "x" referring to??
    Code:
    // get your element
    var x = document.getElementById('yourelement');
    // extract the number from the className
    var current = Number(x.className.match(/(\d+)/)[1]);
    // replace this number with +1 number
    if(current<=358) x.className = x.className.replace(/\d+/, current+1);

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,506
    Thanks
    77
    Thanked 4,378 Times in 4,343 Posts
    That code just makes no sense at all.

    As written, you will be simply dumping what LOOKS like JavaScript AS TEXT into the contents of your <div id="demo">.

    Total nonsense.
    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
    •