Imagine you have an array with 5 items, each containing objects. To visually represent this, elements must be created in the document according to the length of the array. Here's how:
let array = [
{
"value": "Hello"
},
{
"value": "World"
},
{
"value": "You Can"
},
{
"value": " NOT"
},
{
"value": "<h1>Remove ME!</h1>"
}
]
// Creating visual elements based on the array.
for(let i = 0; i < array.length; i++) {
const div = document.createElement("div");
div.classList.add("DIV");
div.innerHTML = `
<span class="Text">${array[i].value}</span>
<span class="Remove">( Remove )</span>
`
document.body.appendChild(div);
}
document.querySelectorAll(".Remove").forEach(elem => {
elem.addEventListener("click", () => {
remove();
})
})
function remove() {
// How do we remove a specific item from the array?
}
// I hope this explanation is clear.
/* CSS IS OPTIONAL */
.DIV {
padding: 10px;
margin: 10px;
background: purple;
color: #fff;
border-radius: 10px;
display: flex;
justify-content: space-between;
}
.Remove {
cursor: pointer;
height: fit-content;
}
If you wish to remove the 4th element (with the value "NOT") by clicking its corresponding remove button, how can you achieve that task in all elements?
(Ensure your code works for all elements.)
Any assistance will be greatly appreciated. Thank you.