I’m new to JavaScript and HTML. I’m reading my JSON file and appending it to each HTML ID but was wondering if there’s an easier way to do this by using a for-loop?
JavaScript
x
26
26
1
$("#vid0")
2
.append(`<video src="${info.data[0].assets[3].url}" poster="${info.data[0].thumbnails[2].url}" muted>
3
</video>
4
<h3 class="title">${info.data[0].metadata.title}</h3><h4 hidden class="description">${info.data[0].metadata.description}</h4>`);
5
6
$("#vid1")
7
.append(`<video src="${info.data[1].assets[3].url}" poster="${info.data[1].thumbnails[2].url}" muted>
8
</video>
9
<h3 class="title">${info.data[1].metadata.title}</h3><h4 hidden class="description">${info.data[1].metadata.description}</h4>`);
10
11
$("#vid2")
12
.append(`<video src="${info.data[2].assets[3].url}" poster="${info.data[2].thumbnails[2].url}" muted>
13
</video>
14
<h3 class="title">${info.data[2].metadata.title}</h3><h4 hidden class="description">${info.data[2].metadata.description}</h4>`);
15
16
$("#vid3")
17
.append(`<video src="${info.data[3].assets[3].url}" poster="${info.data[3].thumbnails[2].url}" muted>
18
</video>
19
<h3 class="title">${info.data[3].metadata.title}</h3><h4 hidden class="description">${info.data[3].metadata.description}</h4>`);
20
21
$("#vid4")
22
.append(`<video src="${info.data[4].assets[3].url}" poster="${info.data[4].thumbnails[2].url}" muted>
23
</video>
24
<h3 class="title">${info.data[4].metadata.title}</h3><h4 hidden class="description">${info.data[4].metadata.description}</h4>`);
25
26
Advertisement
Answer
Iterating over the changing indicies of 0 to 4 would look to do the trick.
JavaScript
1
9
1
for (let i = 0; i < 5; i++) {
2
$(`#vid${i}`)
3
.append(`
4
<video src="${info.data[i].assets[3].url}" poster="${info.data[1].thumbnails[2].url}" muted>
5
</video>
6
<h3 class="title">${info.data[i].metadata.title}</h3><h4 hidden class="description">${info.data[i].metadata.description}</h4>
7
`);
8
}
9
If info.data
will have the same number of items in the array as there are vid elements, a more elegant approach would be to give all such vid elements a class in common (such as vid
), and then do
JavaScript
1
9
1
info.data.forEach((videoData, i) => {
2
$('.vid').eq(i)
3
.append(`
4
<video src="${videoData.assets[3].url}" poster="${videoData.thumbnails[2].url}" muted>
5
</video>
6
<h3 class="title">${videoData.metadata.title}</h3><h4 hidden class="description">${videoData.metadata.description}</h4>
7
`);
8
});
9