Skip to content

Instantly share code, notes, and snippets.

@michaelcpuckett
Created March 14, 2024 22:55
Show Gist options
  • Select an option

  • Save michaelcpuckett/5a5eabeb4a11ccc5ec9e95739c722447 to your computer and use it in GitHub Desktop.

Select an option

Save michaelcpuckett/5a5eabeb4a11ccc5ec9e95739c722447 to your computer and use it in GitHub Desktop.

Revisions

  1. michaelcpuckett created this gist Mar 14, 2024.
    57 changes: 57 additions & 0 deletions api-example.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    <!DOCTYPE html>
    <figure>
    <figcaption>U.S. Population over Time</figcaption>
    <table>
    <thead>
    <tr>
    <th scope="col">Year</th>
    <th scope="col">Population</th>
    </tr>
    </thead>
    <tbody id="result"></tbody>
    </table>
    </figure>
    <script type="module">
    (async function () {
    const API_URL =
    "https://datausa.io/api/data?drilldowns=Nation&measures=Population";
    const responseJson = await fetch(API_URL).then((response) =>
    response.json()
    );
    const populationData = responseJson.data;

    if (!populationData) {
    throw new Error("No population data found.");
    }

    const tbodyElement = window.document.querySelector("#result");

    if (!tbodyElement) {
    throw new Error("No tbody element found.");
    }

    const documentFragment = window.document.createDocumentFragment();

    for (const populationYearItem of populationData) {
    const trElement = window.document.createElement("tr");

    const thElement = window.document.createElement("th");
    thElement.setAttribute("scope", "row");

    const tdElement = window.document.createElement("td");

    const year = populationYearItem["ID Year"];
    const population = populationYearItem["Population"];

    thElement.textContent = year;
    tdElement.textContent = population;

    trElement.append(thElement);
    trElement.append(tdElement);

    documentFragment.append(trElement);
    }

    tbodyElement.append(documentFragment);
    })();
    </script>