To achieve this, you can utilize string interpolation and array index lookup, especially if you are working with ES6.
<script>
var audioFiles = [
"file1.wav",
"file2.wav",
"file3.wav",
];
for(var i = 0; i < 3; i++){
document.body.innerHTML = document.body.innerHTML + `
<audio controls>
<source src="${audioFiles[i]}"; type="audio/wav">
</audio>
`
};
</script>
Nevertheless, there are a few points worth mentioning:
Firstly, it is standard practice not to start variable names with capital letters. So, it would be better to use audioFiles
instead of AudioFiles
. Capitalization is typically reserved for classes and constructors.
Secondly, directly appending elements into the DOM in the manner shown may not be the most optimal approach.
Consider using the appendChild
function: https://www.w3schools.com/jsref/met_node_appendchild.asp
Thirdly, you can simplify the process by utilizing the forEach
function, eliminating the need for a manual counter, which enhances readability and reduces potential errors:
<script>
var audioFiles = [
"file1.wav",
"file2.wav",
"file3.wav",
];
audioFiles.forEach(function(item) {
document.body.innerHTML = document.body.innerHTML + `
<audio controls>
<source src="${item}"; type="audio/wav">
</audio>
`
});
</script>
This method will iterate over each item in audioFiles
, passing it as item
to the iterator function.
However, there's an even more efficient way...
<script>
var audioFiles = [
"file1.wav",
"file2.wav",
"file3.wav",
];
document.body.innerHTML =
document.body.innerHTML +
audioFiles.map(function(item) {
return `
<audio controls>
<source src="${item}"; type="audio/wav">
</audio>
`}).join();
</script>
By using the map function, we reduce repetition and minimize potential mistakes.
The map function transforms an array into another array based on the iterator function provided.