1

How would access all the div's that have been linearly declared through jquery. Here I am trying to make loop through them using a variable 'l'. And it holds the class name.

<html>
<div class="t0"></div>
  <div class="t1"></div>
<div class="t2></div>
  <div class="t3"></div>
  <div class="t4"></div>
</html>
<script>
    var holder = ["cretetion", "OgamingSC2", "ESL_SC2", "FreeCodeCamp", "pewdiepie"];
var holderName;
for (var i = 0; i < holder.length; i++) {
  holderName = holder[i];
  var url = "https://api.twitch.tv/kraken/streams/" + holder[i] + "?callback=?";

  $.getJSON(url, function(data) {
      var l = ".t" + i;
      console.log("Value of l is " + l);

      $(l).html("<button class='btn btn-primary'>" +holderName+"</button>");


  });
}
</script>
  • See [Calling an asynchronous function within a for loop in JavaScript](http://stackoverflow.com/questions/13343340/calling-an-asynchronous-function-within-a-for-loop-in-javascript) – 4castle Apr 03 '16 at 13:51
  • Important to understand that when the ajax callback is being called that `i` is already at it's max value because the `for` loop is done long before the requests start returning data – charlietfl Apr 03 '16 at 13:56
  • [Here is how you should fix your code](https://jsfiddle.net/9bygy6kd/) – 4castle Apr 03 '16 at 14:08
  • @4castle thanks a lot. I didn't know anything about it. Thanks a lot. – Akshat Malik Apr 03 '16 at 14:12
  • You're welcome :) Sorry the question was closed before I could answer. – 4castle Apr 03 '16 at 14:13

2 Answers2

0

if you name divs with a unique prefix you can use attribute selector wildcars

if you name them with id:

$("[id^=mydiv_]")

if you name them with classes:

$("[id*=mydiv_]")
saadin
  • 91
  • 1
  • 8
-1

Pretty simple actually, a prefixed sizzle selector and .each() would look like:

$("div[class^=t]").each(function(i){
   var t_sub_i = $(this); //this is the div itself.
   //i is the 0,1,2...
});
Michael Angstadt
  • 880
  • 10
  • 18