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 Object-Oriented JavaScript (2015) Constructor Functions and Prototypes Making the UI Work

matthew glen
matthew glen
14,153 Points

Help with refactoring, please.

I'm working back through the object-orientated Javascript course, one of the methods is creating a html string to use in a UL list.

Song.prototype.toHTML = function() { let htmlString = '<li'; if (this.isPlaying) { htmlString += ' class="current"'; } htmlString += '>'; htmlString += this.title; htmlString += ' - '; htmlString += this.artist; htmlString += '<span class="duration">'; htmlString += this.duration; htmlString += '</span></li>'; return htmlString; };

My question is, can i refactor this code to use a template literal and how do i include the if statement within that?

1 Answer

Gabbie Metheny
Gabbie Metheny
33,778 Points

If you're using ES6 and template literals, you can just create an li element, set its textContent, then conditionally add a className:

const li = document.createElement('li');
li.textContent = `${this.title} - ${this.artist}`;
if (this.isPlaying) {
  li.className = 'current';
} else {
  li.className = '';
}

You can also create the span in this way, and use appendChild to add it to the li, then return the li at the end of your function. Let me know if you get stuck!