×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Gary Peach
Added: Nov 28, 2017 3:01 PM
Views: 3
superheroes
  1. <body>
  2.  
  3.       <header>
  4.  
  5.       </header>
  6.  
  7.       <section>
  8.  
  9.       </section>
  10.  
  11.     <script>
  12.     var header = document.querySelector('header');
  13.     var section = document.querySelector('section');
  14.  
  15.     var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
  16.     var request = new XMLHttpRequest();
  17.     request.open('GET', requestURL);
  18.     request.responseType = 'json';
  19.     request.send();
  20.  
  21.     request.onload = function() {
  22.       var superHeroes = request.response;
  23.       populateHeader(superHeroes);
  24.       showHeroes(superHeroes);
  25.     }
  26.  
  27.     function populateHeader(jsonObj) {
  28.       var myH1 = document.createElement('h1');
  29.       //myH1.textContent = jsonObj['squadName'];
  30.       //header.appendChild(myH1);
  31.  
  32.       var myPara = document.createElement('p');
  33.       //myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
  34.       //header.appendChild(myPara);
  35.  
  36.     }
  37.  
  38.     function showHeroes(jsonObj) {
  39.       var heroes = jsonObj['members'];
  40.  
  41.       for(var i = 0; i < heroes.length; i++) {
  42.         var myArticle = document.createElement('article');
  43.         var myH2 = document.createElement('h2');
  44.         var myPara1 = document.createElement('p');
  45.         var myPara2 = document.createElement('p');
  46.         var myPara3 = document.createElement('p');
  47.         var myList = document.createElement('ul');
  48.  
  49.         myH2.textContent = heroes[i].name;
  50.         myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity;
  51.         myPara2.textContent = 'Age: ' + heroes[i].age;
  52.         myPara3.textContent = 'Superpowers:';
  53.  
  54.         var superPowers = heroes[i].powers;
  55.         for(var j = 0; j < superPowers.length; j++) {
  56.           var listItem = document.createElement('li');
  57.           listItem.textContent = superPowers[j];
  58.           myList.appendChild(listItem);
  59.         }
  60.  
  61.         myArticle.appendChild(myH2);
  62.         myArticle.appendChild(myPara1);
  63.         myArticle.appendChild(myPara2);
  64.         myArticle.appendChild(myPara3);
  65.         myArticle.appendChild(myList);
  66.  
  67.         section.appendChild(myArticle);
  68.       }
  69.     }
  70.  
  71.     </script>
  72.   </body>