What are some techniques for concealing a rendered element retrieved using the fetch API?

Currently, I am grappling with a coding challenge that requires me to extract data from https://jsonplaceholder.typicode.com/users using the fetch API function along with bootstrap and jquery. To display the data in a div element, I utilized the array.map(). Here is the vanilla JS version of the code executed within the HTML script tags.

However, I encountered an obstacle while attempting to hide the element upon clicking the Delete button. Despite trying callback functions and 'onclick' events for buttons, I have not been able to solve this issue. Can anyone provide guidance on the right approach to tackle this?

Thank you!

<!DOCTYPE html> 
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UI Demo</title>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ae8e5e5fef9fef8ebfacabfa4baa4b8">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c1e1313080f080e1d0c3c49524c524d">[email protected]</a>/dist/js/bootstrap.min.js"> 
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> 
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="css/style.css">

</head>
<body>


<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
   <div class="container-fluid">
     <span class="navbar-brand" href="#">Test App</span>
     <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
       <span class="navbar-toggler-icon"></span>
     </button>
     <div class="collapse navbar-collapse" id="navbarSupportedContent">
       <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        
         <li class="nav-item dropdown bg-light" >
           <a class="nav-link dropdown-toggle text-dark" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
             Menu
           </a>
           <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
             <li><a class="dropdown-item" href="#">Menu 1</a></li>
             <li><a class="dropdown-item" href="#">Menu 2</a></li>
             <li><a class="dropdown-item" href="#">Menu 3</a></li>
           </ul>
         </li>

       </ul>
     </div>
   </div>
 </nav>

   <main>
       <div class="container" id="box">
           <h3>Showing </h3>
           <div class="row">
              <!-- Fetched data gets inserted here -->
                              
             </div>
           </div>
   </main>
   <script>
 
 
   fetch('https://jsonplaceholder.typicode.com/users').then((data) => {
       // console.log(data);
       return data.json();
   }).then((jsondata) => {
 
      
       const names = jsondata.map((values)=> {
          return `<div class="col col-lg-4 col-md-4 gx-4 gy-4">
                       <div id="card" class="card p-2">
                           <h2 id="user">${values.name}</h2>
                               <div class="card-body">
                                 <p><strong>Street:</strong> ${values.address.street}</p>
                                 <p><strong>Suite:</strong> ${values.address.suite}</p>
                                 <p><strong>City:</strong> ${values.address.city}</p>
                                 <p><strong>Zip Code:</strong> ${values.address.zipcode} 
  </p>
                                 <button "class="btn btn-primary float-end"><span><i class="fa-solid fa-trash-can"></i> </span>Delete</button>
                               </div>
                       </div>
                   </div>`
            
       })
      
    
       // document.getElementById('user').innerHTML = names;
       document.querySelector('.row').innerHTML = names;
</script>

Answer №1

  1. Make sure to assign an id to the card element.
  2. Create a click event that removes the DOM element when triggered.
  3. If you want to avoid having commas in your array, use array.join().

Note that removing items from the backend/database requires making another API call.

Here is the final result:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>UI Demo</title>
    <link
      href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adcfc2c2d9ded9dfccdded98839d839f">[email protected]</a>/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06646969727572746776463328362837">[email protected]</a>/dist/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font- awesome/6.1.1/css/all.min.css"
      integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    />
    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
      <div class="container-fluid">
        <span class="navbar-brand" href="#">Test App</span>
        <button
          class="navbar-toggler"
          type="button"
          data-bs-toggle="collapse"
          data-bs-target="#navbarSupportedContent"
          aria-controls="navbarSupportedContent"
          aria-expanded="false"
          aria-label="Toggle navigation"
        >
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav me-auto mb-2 mb-lg-0">
            <li class="nav-item dropdown bg-light">
              <a
                class="nav-link dropdown-toggle text-dark"
                href="#"
                id="navbarDropdown"
                role="button"
                data-bs-toggle="dropdown"
                aria-expanded="false"
              >
                Menu
              </a>
              <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                <li><a class="dropdown-item" href="#">Menu 1</a></li>
                <li><a class="dropdown-item" href="#">Menu 2</a></li>
                <li><a class="dropdown-item" href="#">Menu 3</a></li>
              </ul>
            </li>
          </ul>
        </div>
      </div>
    </nav>

    <main>
      <div class="container" id="box">
        <h3>Showing</h3>
        <div class="row">
          <!-- Insert fetched data here -->
        </div>
      </div>
    </main>

<script>
  function deleteCard(id) {
    document.getElementById(id).remove();
  }
  fetch("https://jsonplaceholder.typicode.com/users")
    .then((data) => {
      return data.json();
    })
    .then((jsondata) => {
      console.log(jsondata);
      const names = jsondata.map((values) => {
        return `<div class="col col-lg-4 col-md-4 gx-4 gy-4" id="${values.id}">
                  <div id="card" class="card p-2">
                    <h2 id="user">${values.name}</h2>
                    <div class="card-body">
                      <p><strong>Street:</strong> ${values.address.street}</p>
                      <p><strong>Suite:</strong> ${values.address.suite}</p>
                      <p><strong>City:</strong> ${values.address.city}</p>
                      <p><strong>Zip Code:</strong> ${values.address.zipcode}</p>
                      <button onclick="deleteCard(${values.id})" "class="btn btn-primary float-end"><span><i class="fa-solid fa-trash-can"></i> </span>Delete</button>
                    </div>
                  </div>
                </div>`;
      });
      document.querySelector(".row").innerHTML = names.join("");
    });
</script>
  </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate a table containing information organized by category

I am looking to create a component Table that groups countries together. Here is my mockup: enter image description here I am struggling to find a solution for this issue. Can someone please assist me? ...

Exploring the scope of event listeners in jQuery's TimeCircles

Currently experimenting with the jquery timer known as "TimeCircles", which can be found here. I have successfully set up a minute / second timer for 30 minutes with an alert that triggers at 25 minutes. My goal is to implement an event when the timer hits ...

`18n implementation in Node.js and front-end JavaScript for localization`

I am currently utilizing express js 4.0 and have set up the i18n module from https://github.com/mashpie/i18n-node in combination with ejs views. My goal is to extend this i18n functionality to .js files as well. Is there a way to enable the i18n function ...

Electron JS-powered app launcher for seamless application launching

Currently, I am working on a project to develop an application launcher using HTML, CSS, and JS with Electron JS. Each application is linked through an a href tag that directs users to the respective application path. If a normal link is used in the a hr ...

Getting the text from a Selenium element can become tricky when dealing with product discounts that alter the element

(Programming) I am working on selecting random products from a website, some with discounts and some without. For instance: How do I retrieve product 748 (without discount)? or How do I retrieve product 419 (with discount)? When the product ha ...

Exploring the process of assigning responses to questions within my software program

I am looking to display my question choices as radio buttons in a modal window. I have tried several solutions without success. Here is my question module: import questions from "./Data"; const QuestionModel = () => { return ( <div cl ...

elements that do not adhere to set width constraints

I've successfully arranged elements in my HTML using flexbox to achieve a responsive design for a website. However, I've encountered an issue where the elements do not resize properly. After applying a class of flex to the home-promos div and re ...

Next.js app encounters a BSON error when using TypeORM

Currently, I am in the process of integrating TypeORM into my Next.js application. Despite utilizing the mysql2 driver and configuring 5 data sources, I am encountering a persistent BSON error: ./node_modules/typeorm/browser/driver/mongodb/bson.typings.js ...

Examining a feature by solely utilizing stubs

I've been immersed in writing tests for the past few weeks. In my workplace, we utilize Mocha as our test runner and Chai for assertions, with Sinon for creating stubs. However, there's a recurring issue that's been bothering me. I've w ...

Verify if the second list item contains the "current" class

When displaying a list of blog items on the blog page, I am using grid-column: 1 / -2;. In the first row, the first blog item spans two columns while the second and subsequent rows display three items in each row. This setup works well, but when moving to ...

The art of perfect alignment: Mastering the positioning of Material-UI Grid

This issue has been resolved Hey there, I'm currently working on a React App with Material-UI and I'm trying to center a Grid item that includes a Card along with two additional Grid items. Below is the relevant code snippet. Although the Cards ...

Partial views within a nested hierarchy are not updating as expected

I am currently working on a partial view that has the following structure: @model ComPost.Core.CommandsAndQueries.Contract.DataContract.FinalizeScreenDTO <div class="row"> <p> <table id="ProductTable"> <tr><td> ...

How can I achieve the same functionality as C# LINQ's GroupBy in Typescript?

Currently, I am working with Angular using Typescript. My situation involves having an array of objects with multiple properties which have been grouped in the server-side code and a duplicate property has been set. The challenge arises when the user updat ...

Content formatted with a gap

I wish to include a gap between each sample usage with markdown. For instance: .kick Sarah, .kick John, .kick Mary .setDescription(`**Usage :** \`${settings.prefix}${command.help.name} ${command.help.usage}\`\n**Example :** \`${setting ...

The animation feature in Angular JS seems to be malfunctioning

Currently in the process of creating a slideshow using AngularJS, similar to the one found at this link, which includes navigation arrows (next and prev). Here is the HTML code snippet: <div class="carousel"> <div class="left"><input ty ...

Utilizing a dedicated settings configuration in a JSON file

I'm interested in finding out how to implement a separate file in Angularjs for storing settings data. For example, I have a service that contains a list of languages like this: .service('Language', function () { this.getLanguageSettings ...

How can I pass command line variables into an npm script?

I am facing an issue where I am attempting to pass a command line option (which is not stored in version control) to my main script index.js. This script performs specific actions based on a designated S3 bucket. Here is the relevant section from my packa ...

Issue with function operation

Incorporating HTML code with Angular elements on the homepage of a PHP forum script has been challenging. I have inserted the PHP code into index.template.php as instructed, but unfortunately, nothing is being displayed. <?php /** * This function ...

Inserting multiple rows in MySql using JavaScript through a URL pathUnique: "

Hello there! I am currently attempting to send an array of objects to my MySql Database via an API endpoint. Below is the code snippet from my API: app.get("/orderdetails/add", (req, res) => { const { item__, Qty_Ordered, Unit_Price, ...

How to divide and access a particular cell in Angular?

I am working with an object called flight.flight_number. Within this object, flight.flight_number is set to: a11;g73;jb87;dd45; The flight.flight_name values are London;Berlin;Torino;Rome; Each value is separated by ';' Here is the code I hav ...