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 trialguram dgebuadze
Front End Web Development Techdegree Student 4,122 PointsArrays-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
Dima Fedin
7,651 PointsSay 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>
...
guram dgebuadze
Front End Web Development Techdegree Student 4,122 Pointsthank you, for your help. But I don't know yet these things, I meant only about function-array - for loop use.