Skip to content

Instantly share code, notes, and snippets.

@michaelcpuckett
Created March 14, 2024 22:55
Show Gist options
  • Save michaelcpuckett/5a5eabeb4a11ccc5ec9e95739c722447 to your computer and use it in GitHub Desktop.
Save michaelcpuckett/5a5eabeb4a11ccc5ec9e95739c722447 to your computer and use it in GitHub Desktop.
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment