Search code examples
javascripthtmljquerydomecmascript-2016

How to remove child element from div using jquery or normal JS


I have a list of user cards. That card contains add and remove button.
I want to remove that card from list of card when I click at remove button.

Code is similar to following:

// function to generate card
function generateUserCard(id) {
  return `
    <div class="user-card" id="${id}">
      <button data-id="${id}" class="add" >Add</button>
      <button data-id="${id}" class="remove" >Remove</button>
    </div>
  `;
}

// function to generate list of user 
function generateUsers(users) {
  const userGrid = $("#user-grid");
  for(let user of users) {
    const userCard = generateUserCard(user.id);
    userGrid.append(userCard);
    // adding event listeners
    $(`[data-id=${user.id}]`).on("click", function() {
       // I did something like this
       (`#${user.id}`).remove(); // But this didn't work
    })
  }
}

Please help!


Solution

  • There are several issues in the logic used in your click event callback:

    • The variable id is not accessible in the callback. A quick fix will be to fix the reference so that you are using user.id in the selector instead. Also, you can simply remove it by ID without needing to search for it inside its parent element, since it is unique.
    • Your selector [data-id]=${user.id} is syntacically incorrect. I suppose you meant [data-id=${user.id}]
    • You should be using .remove() to remove a node

    A quick fix will look like this:

    $(`button[data-id=${user.id}].remove`).on("click", function() {
       $(`#${user.id}`).remove();
    });
    

    See proof-of-concept below:

    function generateUserCard(id) {
      return `
        <div class="user-card" id="${id}">
          User ID: ${id}
          <button data-id="${id}" class="add" >Add</button>
          <button data-id="${id}" class="remove" >Remove</button>
        </div>
      `;
    }
    
    function generateUsers(users) {
      const userGrid = $("#user-grid");
      for (let user of users) {
        const userCard = generateUserCard(user.id);
        userGrid.append(userCard);
    
        $(`button[data-id=${user.id}].remove`).on("click", function() {
          $(`#${user.id}`).remove();
        })
      }
    }
    
    // For demo only
    let i = 0;
    $('#btn').on('click', function() {
      const userArray = [];
      for (let j = 0; j < 3; j++) {
        i++;
        userArray.push({ id: i });
      }
      generateUsers(userArray);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="btn">Generate users</button>
    <div id="user-grid"></div>

    However, an improvement to your code will be to avoid adding new click event listeners to all your newly appended elements. You can simply listen to the click event bubbling up to a parent that is already present at runtime (e.g. #user-grid), and you can bind it outside of your generateUsers function:

    $('#user-grid').on('click', 'button.add, button.remove', function() {
      const id = $(this).attr('data-id');
      $(`#${id}`).remove();
    });
    

    See proof-of-concept below:

    function generateUserCard(id) {
      return `
        <div class="user-card" id="${id}">
          User ID: ${id}
          <button data-id="${id}" class="add" >Add</button>
          <button data-id="${id}" class="remove" >Remove</button>
        </div>
      `;
    }
    
    function generateUsers(users) {
      const userGrid = $("#user-grid");
      for (let user of users) {
        const userCard = generateUserCard(user.id);
        userGrid.append(userCard);
      }
    }
    
    // Listen to event bubbling instead!
    $('#user-grid').on('click', 'button.remove', function() {
      const id = $(this).attr('data-id');
      $(`#${id}`).remove();
    });
    
    // For demo only
    let i = 0;
    $('#btn').on('click', function() {
      const userArray = [];
      for (let j = 0; j < 3; j++) {
        i++;
        userArray.push({
          id: i
        });
      }
      generateUsers(userArray);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="btn">Generate users</button>
    <div id="user-grid"></div>