I am writing a simple program to list some elements from an array and then the user can input a value thats gets pushed to that array, but for some reason the array is not showing the updated array. I can see the additional values getting pushed into it but the UI is not updating? Perhaps it is the order of the code?
code:
// Data structure
const planets = [
'Mercury',
'Venus',
'Earth'
];
// Loop over array
const func = (arr) => {
let items = '';
for (let i = 0; i < arr.length; i++) {
items += `<li>${ arr[i] }</li>`;
}
return items;
}
let html = `
<ul>
${func(planets)}
</ul>
<button id='myButton'> Add </button>
`;
document.querySelector('main').innerHTML = html;
// add to array
const addFunc = () => {
const searchQuery = prompt('What do you want to add?');
const search = newArray.push(searchQuery);
}
const myButton = document.getElementById('myButton');
myButton.addEventListener('click', () => {
addFunc();
});
.innerHTML = html;, which only runs once when the page loads, as it is not inside your addFunc()htmlstring and performs the.innerHTMLinto a function of its own (eg: updateUI). You can call this function when the page loads, and also call it once you add an item to your array. Anotther way would be to leave your code as is and use.innerHTML = `<li>${ searchQuery }</li>`;as the last line in your addFunc