Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท Building AJAX User Interfaces

Rendering API Data in the DOM

Turn fetched JSON into safe DOM nodes, understand textContent versus innerHTML, use the template element, and show loading, empty and error states.

Fetching JSON is only half of an AJAX feature. The data has to appear on the page, and it has to do so safely, because API data is not under your control. A product name, a comment or a username may contain characters that browsers treat as HTML. If you paste such text into the page as markup, you may let an attacker run code in your visitors' browsers.

This lesson shows how to build DOM nodes from a list of objects, why textContent is the default choice and innerHTML the exception, how the <template> element keeps your markup tidy, and how to design the three states every data-driven screen needs: loading, empty and error. Basics of requests are in Your First fetch() Request.

From JSON to elements

Suppose the API returns this list:

JSON
[
  { "id": 1, "name": "Mia", "role": "Designer" },
  { "id": 2, "name": "Noah", "role": "Engineer" }
]

The rendering recipe is always the same: create elements with document.createElement(), fill them with textContent, add classes or attributes, and append them. Build the whole list first, then insert it once, so the page does not re-layout for every row.

flowchart LR
    A["fetch()"] --> B["response.json()"]
    B --> C{"Any items?"}
    C -- "yes" --> D["createElement + textContent"]
    C -- "no" --> E["Empty message"]
    D --> F["replaceChildren()"]
    E --> F

Data flows from the response to DOM nodes; empty results get their own message.

The TryIt below contains a mock API (a function that returns a Response after a short delay, so no real server is needed) and a renderer. Press the button to load the team.

Build a list with createElement

replaceChildren() clears the list and inserts the new nodes in one step, so pressing the button twice does not duplicate rows.

textContent versus innerHTML

textContent treats everything as plain text. innerHTML parses the string as HTML. With untrusted data the difference is the whole story. The next demo uses a harmless <b> tag as the "attack" so you can see what the browser does with it; a real attack would use a script-running payload instead of bold text.

textContent is safe, innerHTML parses markup

The textContent line shows the tag characters exactly as received. The innerHTML line turned them into real bold text, because the browser trusted the string. If that string had contained an element with an event handler, the handler would run. The rule:

  • Use textContent (or createElement with setAttribute) for any value that came from outside your code.
  • Use innerHTML only for markup you wrote yourself, or after the content passed through a trusted sanitizer.
  • Never build attribute or URL values by string concatenation. Check that URLs begin with https:// before using them in href or src, because javascript: URLs are executable.

There is more on this attack in AJAX Security.

Templates

Building every element by hand gets long for rich cards. The <template> element holds inert markup that the browser parses but never displays. You clone it, fill in the holes with textContent, and insert the clone. The markup stays in HTML where designers can read it, and the data still goes in as text.

Cards from a template element

The second product's title contains a tag, and it appears as literal text, proof that the template approach is safe. Remember cloneNode(true): without true you copy only the empty wrapper.

Loading, empty and error states

A screen that fetches data is never just "the list". It is in one of four states: idle, loading, success (with items, or with none), or error. Users forgive waiting and failure when the page says what is going on. They do not forgive a blank area.

stateDiagram-v2
    [*] --> Loading
    Loading --> Success: items arrived
    Loading --> Empty: zero items
    Loading --> Error: network or HTTP failure
    Error --> Loading: Retry
    Success --> Loading: Refresh

A data-driven view moves between loading, success, empty and error; Retry and Refresh go back to loading.

Keep the state in one place and render from it. This final example has three mock endpoints, one for each outcome, plus aria-live so screen readers announce changes (see Cancelling Requests and Timeouts for what to do when a user triggers several loads quickly).

All four states with a mock API

Try each button. The yellow message appears for the 400 ms the mock server takes, the empty list gets a calm grey explanation, and the broken endpoint gives a red message that mentions the status code. Note that response.ok is checked before parsing, because a 500 response is not a network failure and fetch() does not reject for it (see Handling Errors in fetch).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. An API returns a username containing HTML tags. Which assignment shows it as plain text?

    textContent never parses markup, so tags appear literally and cannot run code.
  2. 2. Why does replaceChildren(...items) beat appendChild in a loop on every refresh?

    replaceChildren swaps the whole content at once, so repeated loads never leave duplicates or flicker.
  3. 3. What must you do to a template's content before inserting it?

    template.content is inert and reusable; each use needs a deep clone.
  4. 4. Which states should a data-driven list handle?

    An empty array is a normal API answer and errors do happen; each needs a visible message.

Summary

  • Build nodes with createElement, fill them with textContent, and insert them with replaceChildren().
  • innerHTML parses markup, so use it only for trusted strings; never for API values.
  • A <template> keeps markup in HTML; clone with cloneNode(true) and fill the holes with text.
  • Always design loading, empty and error states, and announce changes with aria-live.

Next: Submitting Forms with AJAX.