Home > other >  How do you make an alert from API become text on a webpage?
How do you make an alert from API become text on a webpage?

Time:12-16

I have it set up so you have a list of countries and when you click on it it gives a pop-up with the sub region and then shows the country flag next to the country. How can I change it so that the sub region shows up with the flags using my API?

var xhttp = new XMLHttpRequest();
var respJSON = [];
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    resp = this.responseText;
    respJSON = JSON.parse(resp);

    html = document.getElementById("list");
    html.innerHTML = "";

    for (var i = 0; i < respJSON.length; i  ) {
      html.innerHTML  = "<li id="   i   " onClick='clickMe("   i   ")'>"   respJSON[i].name   "</li>"
    }
  }
}
//connect our api
xhttp.open("GET", "https://restcountries.com/v2/all", true);
xhttp.send();

function clickMe(index) {
  li = document.getElementById(index);
  img = document.createElement("img")
  img.src = respJSON[index].flag;
  li.append(img); 
  {
    //create subregion text on website
    //unsure how to make it show as text and not as a pop-up
    alert(respJSON[index].subregion);
  }
}

CodePudding user response:

Create a DIV or SPAN element and put the subregion in its text. Then append this to the LI after the image.

function clickMe(index) {
  let li = document.getElementById(index);
  let img = document.createElement("img")
  img.src = respJSON[index].flag;
  li.append(img); 
  let div = document.createElement("div");
  div.innerText = respJSON[index].subregion;
  li.append(div);
}
  • Related