Iterating through multiple div ids

I'm trying to make a site that displays 90 individual div boxes, then prompt an age number. Then use that answer to shade in the the answer amount of boxes out of 90.

How can I get the divs in the last for-loop to iterate through the divs?

      for(i = 0; i < 90; i++) {
      $('body').append('<div id="div'+ i +'" />');
         };

     var answer = prompt("Whats your age");

      for (i = 0; i <= answer; i += 1){
      // how can i get this $('#div') below to iterate through the divs?
      $('#div').css({ "background-color": "red"});

        }

thanks guys

Answers 1

  • Another way to solve this is to use jQuery's filter method.

    $("div[id^='div']").filter(function(index) {
      return index < answer;
    }).css({
      "background-color": "red"
    });
    

    In the code snippet above you get all div's which have an id attribute and start with the div text. Then you filter all these results by index. As long as the current index in the inner loop of filter method is less than the answered, the element will get the red background.

    Filter documentation: http://api.jquery.com/filter/

    Reduce the set of matched elements to those that match the selector or pass the function's test.

    From performance perspective this isn't the best answer as it searches for div elements in DOM which have an id. For better performance you should narrow the search, for example under a container with a specific id.

    Last but not least, here's a plunk. DEMO

    EDIT Almost forgot. You should introduce some condition checks for the user's answer. For example, if the answer was a valid integer, if it is in bounds (0,90), or if the operation was canceled.


Related Articles