Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

guram dgebuadze
seal-mask
.a{fill-rule:evenodd;}techdegree
guram dgebuadze
Front End Web Development Techdegree Student 4,122 Points

Arrays-for loop, listHTML.

the code written is too complicated will this be right choice to write this way listHTML = '<ol>'; for( var i = 0; i < playList.length; i++) { listHTML += '<li>' + playList[i] + '</li>'; } listHTML += '</ol>'; document.write(listHTML);

Code is less and easier to guess.

2 Answers

Dmitry Fedin
Dmitry Fedin
7,650 Points

Say up we have the following HTML markup:

...
<body>
</body>
...

To create playlist which consists of <ol> and <li> elements we need to write the following JS code:

var songs = [
'Song 1',
'Song 2',
'Song 3'
];

var ol = document.createElement('ol');

for (var i = 0; i < songs.length; i++) {
    var li = document.createElement('li');
    li.innerHTML = songs[i];
    ol.appendChild(li);
}

document.body.appendChild(ol);

Also there is a way with using ES6 features:

const songs = [
'Song 1',
'Song 2',
'Song 3'
];

const ol = document.createElement('ol');

songs.forEach((song) => {
    const li = document.createElement('li');
    li.innerHTML = song;
    ol.appendChild(li);
})

document.body.appendChild(ol);

Both methods give you this result:

...
<body>
    <ol>
        <li>Song 1</li>
        <li>Song 2</li>
        <li>Song 3</li>
    </ol>
</body>
...