title: Insert multiple html elements based on dynamic values, into different DIVs using javascript
body: <p>I'm having a bit of trouble trying to figure out what I need to do.</p>
  
  <p>I'm working on a small train timetable app which finds the five closest stations and brings up the timetables for all five stations. I have successfully found the nearest stations, and have managed to get all the service information from each of the stations. I have used datasets on the wrapper element for each station as a way to insert the correct service information to each wrapper.</p>
  
  <p>The problem I'm facing now, is that at the moment I have all of the service box elements being placed in to the first wrapper. Is there a way to insert the service box elements in to the correct DIVs?</p>
  
  <p>The API I am working with provides a unique 3 character station code (e.g. FST etc.), as well as the API I have used to find stations nearby.</p>
  
  <p>e.g I have 5 stations with the codes AAA, AAB, AAC, AAD and AAE. All AAA stations should be inserted in to the respective DIV with the AAA dataset, same with AAB... etc...</p>
  
  <p>I am using the TransportAPI if you need to know.</p>
  
  <p>See the Javascript code I have so far. Thanks in advance.</p>
  
  <pre class="lang-js prettyprint-override"><code>// scripts
  
  // change protocol to https if http
  if (window.location.protocol != 'https:') window.location.protocol = 'https';
  
  // 
  var info = document.querySelector(".info");
  
  // check if geolocation works/is supported using if statement
  // if geolocation is supported
  if ("geolocation" in navigator) {
  
      // log to console
      console.log("GeoLocation is working.");
  
      // function to run if geolocation is supported
      navigator.geolocation.getCurrentPosition(function(position) {
  
          // store users coords
          var lat = position.coords.latitude;
          var lon = position.coords.longitude;
  
          // log them to console
          console.log("Your coordinates are: " + lat + "," + lon);
  
          // callback function to use users coordinates in another function
          findNearestStation(lat, lon);
  
      });
  
      // if geolocation is not supported
  } else {
  
      // log to console
      console.log("GeoLocation is not supported.");
  }
  
  function findNearestStation(lat, lon) {
  
      console.log("Your coordinates are: " + lat + "," + lon);
  
      // api keys and tokens
      var appID = "xxxxx";
      var appKey = "xxxxxxxxxxxx";
  
      // api for nearest stations url template
      var transportApiUrl = "https://transportapi.com/v3/uk/train/stations/near.json?app_id=" + appID + "&amp;app_key=" + appKey + "&amp;lat=" + lat + "&amp;lon=" + lon + "&amp;rpp=5";
  
      // ajax request to get nearest stations
      var nearbyStationsReq = new XMLHttpRequest();
  
      nearbyStationsReq.open('GET', transportApiUrl, true);
  
      nearbyStationsReq.onload = function() {
  
          // results window
          var resultsWindow = document.querySelector(".results-window");
  
          // empty array for the timetable urls
          var timetableUrlArray = [];
          // empty array for station codes
          var stationCodeArray = [];
  
          // clear the results window
          resultsWindow.innerHTML = "";
  
          if (this.status &gt;= 200 &amp;&amp; this.status &lt; 400) {
              // response data
              var res = JSON.parse(this.response);
  
              // variable for stations array in response
              var data = res.stations;
  
              // for loop to iterate through response data
              for (var i = 0; i &lt; data.length; i++) {
  
                  // get information from response data
                  var code = data[i].station_code;
                  var name = data[i].name;
                  var distanceMetres = data[i].distance;
                  var distanceKilometres = (distanceMetres / 1000).toFixed(1);
                  var distanceKilometres = distanceKilometres + "km";
  
                  // log data to console to reference
                  console.log("Code: " + code + " | Name: " + name + " | Distance: " + distanceKilometres);
  
                  // generate urls for timetable data
                  var timetableUrl = "https://transportapi.com/v3/uk/train/station/" + code + "/live.json?app_id=" + appID + "&amp;app_key=" + appKey + "&amp;darwin=true&amp;train_status=passenger";
  
                  // push completed urls to the array
                  timetableUrlArray.push(timetableUrl);
  
                  // push codes to empty array
                  stationCodeArray.push(code);
  
                  // template for nearest stations result container
                  var resultTemplate =
                      "&lt;div class='result'&gt;" +
                      "&lt;div class='station-name'&gt;" +
                      "&lt;span class='service-origin'&gt;" +
                      "&lt;span class='nr-logo'&gt;" +
                      "&lt;img src='assets/images/nr.svg' alt='National Rail Logo'&gt;&lt;/span&gt;" + name + "&lt;/span&gt;" +
                      "&lt;/div&gt;" +
                      "&lt;div class='service-results-wrapper' data-stationcode='" + code + "'&gt;&lt;/div&gt;" +
                      "&lt;/div&gt;";
  
                  // insert template in to the results window
                  resultsWindow.innerHTML += resultTemplate;
  
              }
  
              // log to console
              console.log(stationCodeArray)
  
              // for loop to create a request for each station
              for (var i = 0; i &lt; timetableUrlArray.length; i++) {
  
                  // ajax request for timetable request
                  var timetableReq = new XMLHttpRequest();
                  timetableReq.open('GET', timetableUrlArray[i], true);
  
                  timetableReq.onload = function() {
                      if (this.status &gt;= 200 &amp;&amp; this.status &lt; 400) {
                          // response from request
                          var res = JSON.parse(this.response);
  
                          // data for timetable info
                          var data = res.departures.all;
  
                          // declare service results wrapper
                          var serviceResultsWrapper = document.querySelectorAll(".service-results-wrapper");
  
                          // loop to go through the data
                          for (var i = 0; i &lt; data.length; i++) {
  
                              // information required
                              var currentStation = res.station_name;
                              var currentStationCode = res.station_code;
                              var aimedDepartTime = data[i].aimed_departure_time;
                              var expectedDepartTime = data[i].expected_departure_time;
                              var destination = data[i].destination_name;
                              var platform = data[i].platform;
                              var operator = data[i].operator_name;
                              var status = data[i].status;
                              var trainUID = data[i].train_uid;
  
                              // log data to console
                              console.log("Current Station: " + currentStation + " | Current Station Code: " + currentStationCode + " | Aimed: " + aimedDepartTime + " | Expected: " + expectedDepartTime + " | Destination: " + destination + " | Platform: " + platform + " | Status: " + status + " | Operator: " + operator + " | ID: " + trainUID);
  
                              // template for service boxes
                              var serviceBoxTemplate = "&lt;span class='service-box'&gt;&lt;span class='service-time-status'&gt;&lt;span class='service-depart-time'&gt;" + aimedDepartTime + "&lt;/span&gt;" +
                                  "&lt;span class='service-depart-status'&gt;" + currentStation + "&lt;/span&gt;" +
                                  "&lt;span class='service-depart-platform'&gt;Plat. &lt;span class='service-platform-number'&gt;" + platform + "&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;" +
                                  "&lt;span class='service-destination'&gt;&lt;span class='service-destination-name'&gt;" + destination + "&lt;/span&gt;&lt;/span&gt;" +
                                  "&lt;span class='calling stations'&gt;Leigh-on-Sea, Chalkwell, Westcliff, Southend Central, Southend East, Thorpe Bay, Shoeburyness&lt;/span&gt;" +
                                  "&lt;span class='service-operator'&gt;Operated by &lt;span class='service-operator-by'&gt;" + operator + "&lt;/span&gt;&lt;/div&gt;";
  
                              serviceResultsWrapper[0].innerHTML += serviceBoxTemplate;
  
                          }
  
                      } else {
                          // We reached our target server, but it returned an error
  
                      }
                  };
  
                  timetableReq.onerror = function() {
                      // There was a connection error of some sort
                  };
  
                  timetableReq.send();
  
              }
  
          } else {
              // log to console
              console.log("There is an error.");
  
          }
      };
  
      nearbyStationsReq.onerror = function() {
  
          // log to console
          console.log("There is an error.");
  
  
      };
  
      nearbyStationsReq.send();
  
  }
  </code></pre>