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

Outputting HTML with JavaScript

Hi all,

I'm working on a little program that takes array keys and values, and outputs them into their own individual <div>s and <ul>s. I'm unable to tell why the program isn't working. No warnings or errors are being thrown in the console.

Below, I'll include the JavaScript used in both main.js and hello.js.

// main.js
var movies = [{
  title: 'The Revanant',
  genre: 'Survival',
  release: 4 + '/' + 7 + '/' + 16
}, {
  title: 'Test',
  genre: 'Nonsense',
  release: 6 + '/' + 21 + '/' + 16
}];

// hello.js
var message = '';
var movies;

function print(message) {
  var outputDiv = document.getElementsByClassName("wrap");
  outputDiv.innerHTML = message;
}

for (var i = 0; i < movies.length; i++) {
  var movie = movies[i];
  message += '<div class="floater">';
  message += '<ul>';
  message += '<li>' + movie.title + '</li>';
  message += '<li>' + movie.genre + '</li>';
  message += '<li>' + movie.release + '</li>';
  message += '</ul>';
  message += '</div>';
}

print(message);

Any idea what I'm doing wrong here?

1 Answer

The issue is this line:

var outputDiv = document.getElementsByClassName("wrap");

The getElementsByClassName method will always return a list of HTML elements (technically a HTMLCollection), even when only one element matches the criteria you specify. Since innerHTML is a property belonging to individual elements, not to element lists your code doesn't do what you intend for it to do.

This issues can be solved by pulling out the first item from the element list like this:

var outputDiv = document.getElementsByClassName("wrap")[0];

That way you end up with outputDiv being equal to a single element, or you can use the querySelector method, which will always return the first element it will find. Like this:

var outputDiv = document.querySelector(".wrap");

You could also change wrap from being a class to an id. The getElementById method will also only return a single element, since ids are meant to be unique. So with that you don't have to worry about getting a list of elements back.

Thank you so much! I've been fighting with this for hours now haha! Very appreciated, and thanks for the educational response.