1 | initial version |
To modify the index of an item in an array to correspond with HTML elements, you can use a loop to iterate over the array and create HTML elements with the array values. Here is an example:
// Sample array
let fruits = ["apple", "banana", "orange"];
// Get the element where the fruits will be displayed
let fruitList = document.getElementById("fruit-list");
// Loop through the array and create HTML elements
for (let i = 0; i < fruits.length; i++) {
// Create a list item element
let li = document.createElement("li");
// Set the text content to the array value
li.textContent = fruits[i];
// Set the id attribute to the corresponding index
li.setAttribute("id", "fruit-" + i);
// Add the list item to the fruit list element
fruitList.appendChild(li);
}
In the above example, a loop is used to create a list item element for each value in the fruits
array. The li
element's text content is set to the array value, and its id
attribute is set to "fruit-"
plus the current loop index. This allows you to uniquely identify each list item element based on its corresponding array index. Finally, the li
element is added to the fruitList
element using the appendChild
method.