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 (retiring) jQuery and AJAX The Office Status Project Revisited

$(element).html(content) method

During this video, we wrote the following:

$(document).ready(function () {
  $.getJSON('../data/employees.json', function (data) {
    var statusHTML = '<ul class="bulleted">';
    $.each(data,function (index, employee) {
   if (employee.inoffice === true) {
        statusHTML +='<li class="in">';
      } else {
        statusHTML +='<li class="out">';
      }
      statusHTML += employee.name + '</li>';
    });
    statusHTML += '</ul>';
    /*the confusing line*/ $('#employeeList').html(statusHTML);
  }); // end getJSON
}); // end ready

One line in this code is confusing me A LOT. So basically I marked the confusing line using a comment and here's my question. Does the .html(); method replace the entire html of the element or does it add (append) the html to the element?

3 Answers

It functions the same way as this line in Javascript:

document.getElementById("element").innerHTML = "content";

where element is the element that is affected, and content is what is being put into that element. In other words, it replaces the element's content; it doesn't append to it.

ywang04
ywang04
6,762 Points

Does the .html(); method replace the entire html of the element or does it add (append) the html to the element?

The answer is the .html(); method replaces the entire html. When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content.

.html().

Erik Nuber
Erik Nuber
20,629 Points
$('#employeeList').html(statusHTML);

The first part is getting the location with an ID tag of emplyeeList.

The second part is taking the ul list that was created in this particular video, though it could be any html value given to the variable statusHTML and, it is placing that given html into a specific location. So it would be adding to that location not changing anything else.

Thank You :)

Erik Nuber
Erik Nuber
20,629 Points

I looked it up and actually it lets you add HTML tags and text within an element. Any content previously within the element will be completely replaced with the content you provide using this function. So it does replace whatever was there before...