Home >Web Front-end >JS Tutorial >How to Populate HTML Dynamically with Data from An API
This tutorial demonstrates how to fetch and display data from a Harry Potter character API using JavaScript's fetch()
method. We'll build a webpage dynamically populated with character information.
First, we target the HTML element where character data will be displayed:
<code class="language-javascript">const charsSection = document.getElementById('chars-container');</code>
Next, we define the API URL and an asynchronous function to retrieve and filter the data:
<code class="language-javascript">const charsURL = 'https://hp-api.herokuapp.com/api/characters'; async function getChars() { const response = await fetch(charsURL); const allCharsArr = await response.json(); let newCharsArr = []; for (let i = 0; i < allCharsArr.length; i++) { if (allCharsArr[i].image.length > 0 && allCharsArr[i].species === 'human') { newCharsArr.push(allCharsArr[i]); } } return newCharsArr; }</code>
The getChars()
function fetches data, converts it to JSON, and filters the results to include only human characters with associated images. This filtering addresses potential API incompleteness.
The webpage is populated using this asynchronous function:
<code class="language-javascript">async function buildPage() { const newCharsArr = await getChars(); for (let i = 0; i < newCharsArr.length; i++) { // ... (HTML card creation logic here) ... } }</code>
This buildPage()
function iterates through the filtered character data and dynamically creates HTML elements (character cards) to display the character's image, name, ancestry, Hogwarts house, and actor/actress. The innerHTML
of charsSection
is updated to display these cards. Because getChars()
is asynchronous, buildPage()
must also be asynchronous and await
the result of getChars()
.
The following image shows a sample of the populated webpage. Styling details are omitted for brevity, but the complete project code is available at [link to project].
This example showcases dynamic webpage population using API data. Feedback and sharing are appreciated!
Project in action
Project repo
MDN Web Docs ‘Introduction to Web APIs’
Originally published to Medium for JavaScript in Plain English on November 14, 2022
The above is the detailed content of How to Populate HTML Dynamically with Data from An API. For more information, please follow other related articles on the PHP Chinese website!