I am trying to add data in the array on clicking the button and its happening too and I am using loop over array to show data on the page from array but when the data is added to array is does not on the page.
Change is not reflecting on the page.
If you anyone have any solution kindly provide. Thanks in advance.
const ob = ["first", "second", "third"];
for (let i = 0; i < ob.length; i++) {
const nametag = `<p>${ob[i]}</p>`;
document.querySelector(".name-list").insertAdjacentHTML("beforeend", nametag);
}
function add() {
const value = document.querySelector("textarea").value;
ob.push(value);
}
document.querySelector(".add").addEventListener("click", () => add());
<div class="name-list"></div>
<textarea placeholder="enter name"></textarea><br>
<button class="add">Add Name</button>
2
Answers
You have to update the HTML to add name on clicking the button. You can use
insertAdjacentHTML()
to update the DOM like the following way:There’s no link between JS arrays and your page. You should add the HTML yourself. One way it’s to add reactivity to your array with
Proxy
. Once you push to it, the HTML will be added automatically: