CodeBlanks Logo Icon CodeBlanks

Rendering data to the DOM

JavaScript course · Intermediate · Lesson 93/134

Render fetched data to the UI with template literals and textContent.

Rendering data to the screen

To reflect the server data on screen we use the weatherResult.textContent property. It sets the text content of an element. To combine the city name and the weather info into a single string we use a template literal: inside backticks we embed values with ${variable}. In the example `${city}: ${info}` the city and info values merge into one string. When we assign the result to textContent it appears on screen.

Template literals

A template literal is a string written inside backticks. You can embed values inside it with ${}. Writing `${city} - ${info}` puts the values of the city and info variables into the string. You don't need to concatenate with quotes or plus signs. Template literals can also span multiple lines; instead of the \n escape sequence you can just press enter. This makes it easier to write readable code when rendering data to the screen.

Exercise Define the renderWeather function

Continue on top of the previous lesson's solution. Define a function renderWeather(city, info). Inside it, assign the template literal `${city}: ${info}` to the weatherResult.textContent property. This way the city and weather info are rendered on a single line.

Show example solution
const app = document.querySelector("#app");
const cityInput = document.querySelector("#cityInput");
const getWeatherButton = document.querySelector("#getWeatherButton");
const weatherResult = document.querySelector("#weatherResult");
console.log(app, cityInput, getWeatherButton, weatherResult);

function getWeather() {
  const city = cityInput.value;
  console.log(city);
}

getWeatherButton.addEventListener("click", getWeather);

async function fetchWeather(city) {
  const url = `https://api.example.com/weather?city=${city}`;
  const response = await fetch(url);
  const info = await response.text();
  return info;
}

function renderWeather(city, info) {
  weatherResult.textContent = `${city}: ${info}`;
}

Test yourself

  1. Assign the result with a template literal

    weatherResult.textContent = ____;
    Show answer
    weatherResult.textContent = `${city}: ${info}`;
  2. Which uses a template literal to combine values?

    • 'City: ' + city
    • 'City: ${city}'
    • 'City: city'
    • `${city}: ${info}`
    Show answer

    `${city}: ${info}` — Correct! Backticks and ${} form a template literal.

  3. Match the render steps

    template literal
    Combines the values
    textContent
    Sets the text
    weatherResult
    The target element
    ${info}
    Embeds the info value
  4. Match the renderWeather pieces

    weatherResult.textContent
    Sets the output
    ${city}
    Embeds the city
    ${info}
    Embeds the info

All lessons in Intermediate