Question

I am using jQuery to parse some xml weather information and I can't work out how I can constrain this code to parse only the first 7 weather forecast days, there is a total of 10 forecastdays nodes in the xml but I only want to show 7. My current for loop makes it output each forecastdays node 7 times instead of limiting it to looping just 7 times. Thanks in advance.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  $.ajax({
  type: 'GET',
  url: 'Poole.xml',
  dataType: 'xml',
  success: parseXml
  });
});

function parseXml(xml) {
    $(xml).find('response forecast simpleforecast forecastdays forecastday').each(function() {
        for (var i=0; i<7; i++) {    
          var weekday = $(this).find("date weekday").text();
          var icon_url = $(this).find("icon_url").text();
          var conditions = $(this).find("conditions").text();
          var high = $(this).find("high celsius").text();
          var low = $(this).find("low celsius").text();
          $('<li><span><strong>' + weekday + '</strong></span><span><img src="' + icon_url + '" width="75" height="75" /></span><span>' + conditions + '</span><span>High ' + high + '&#176;C / Low ' + low + '&#176;C</span></li>').appendTo('#weatherContent');   
        }
    });
}
</script>

<ul id="weatherContent"></ul>

You can download a copy of my xml file which I am parsing here: http://temp-share.com/show/2gFHqr478 (Poole.xml)

Was it helpful?

Solution

Use :lt() selector:

$("response forecast simpleforecast forecastdays forecastday:lt(7)", xml)
    .each(function() { ... });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top