skip to Main Content

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


  1. 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:

    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;
    
        //update the HTML for the newly added name
        const nametag = `<p>${value}</p>`;
        document.querySelector(".name-list").insertAdjacentHTML("beforeend", nametag);
    
        //add the new name to the array
        ob.push(value);
    
        //clear the textarea for the next input
        document.querySelector("textarea").value = "";
      }
    
    document.querySelector(".add").addEventListener("click", () => add());
    <div class="name-list"></div>
    <textarea placeholder="enter name"></textarea><br>
    <button class="add">Add Name</button>
    Login or Signup to reply.
  2. 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:

    const ob = new Proxy([], {
      get(arr, prop){
        if(prop === 'push') return function(...args){
          const out = arr.push(...args);
          for(const text of args){
            const nametag = `<p>${text}</p>`;
            document.querySelector(".name-list").insertAdjacentHTML("beforeend", nametag);
          }
          return out;
        }
        return Reflect.get(...arguments);
      }
    });
    
    ob.push("first", "second", "third");
    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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search