Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics Programming AJAX Processing JSON Data

Elias Hass
Elias Hass
10,339 Points

My solution using template literals.

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    let employees = JSON.parse(xhr.responseText);
    const ul = document.createElement("ul");
    ul.className = "bulleted";
    for (let i = 0; i < employees.length; i++) {
      const className =
        employees[i].inoffice === true ? `class="in"` : `class="out"`;
      ul.insertAdjacentHTML(
        "beforeend",
        `<li ${className}>${employees[i].name}</li>`
      );
    }
    document.getElementById("employeeList").appendChild(ul);
  }
};

xhr.open("GET", "data/employees.json");
xhr.send();

3 Answers

Ben McMahan
Ben McMahan
7,922 Points

Nice! Very similar to what I came up with. I like yours better, forgot about those lessons a few days ago LOL

let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        let employees = JSON.parse(xhr.responseText);
        let statusHTML = '<ul class="bulleted">';

        for (i = 0; i < employees.length; i++) {
            let name = employees[i].name;
            let inOffice = employees[i].inoffice;
            let className = inOffice ? 'in' : 'out';
            // Build up the LI element
            statusHTML += `<li class="${className}">${name}</li>`;
        }
        statusHTML += '</ul>'

        document.getElementById('employeeList').innerHTML = statusHTML;
    }
}

xhr.open('GET', 'data/employees.json');
xhr.send();