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

Extracting JSON Value from a Script Tag

Seeking a more efficient method to extract the designated JSON value (highlighted in yellow) that is currently acquired using the code below. Although effective, it lacks efficiency. $("head > script:nth-child(55)").text().trim().replace(" ...

Attempting to create a footer design featuring buttons aligned to the left and right sides

I am trying to create a layout similar to the bottom of Google's homepage using this code. However, no matter what I try, the "lists" are still appearing vertically instead of horizontally. My goal is to have three columns of links positioned side by ...

Using jQuery to vertically center a div

When a vertical menu on my website is clicked, it pops out from the left side of the screen. The content inside is vertically centered using CSS transformations. While expanding to show sub-items, everything remains centered. However, there's an issue ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

Storing the state of DevExtreme DataGrid in Angular

Currently, I have integrated the DevExtreme DataGrid widget into my Angular application. Here is a snippet of how my DataGrid is configured: <dx-data-grid id="gridContainer" [dataSource]="employees" [allowColumnReordering]="true" [allo ...

What is the best way to apply the addClass method to a list element

I've been searching for a solution to this issue for some time now, and while I believed my code was correct, it doesn't appear to be functioning as expected. HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js ...

It appears that the margin is malfunctioning

Let's cut to the chase - I want to add a chat sidebar to my website, but I'm having trouble adding margins to make it close in properly. Here's the code snippet: HTML <div class="inner-chat"> <div class="chat-box-messages"> ...

Using JavaScript, redirect to a specified URL once a valid password has been entered on an HTML form

Need help with JavaScript for password validation and URL redirection. I'm new to JS and used some resources like Password correct? then redirect & Adding an onclick function to go to url in javascript?. Here's my current code: ...

Transferring a PHP array to JavaScript using AJAX

I have spent time searching for answers to my issue with no success. My PHP file includes the following array: $data = ['logged' => $_SESSION['loggedin'], 'sessName' => $_SESSION['name']]; echo json_encode($dat ...

Executing filepicker.io Javascript API calls may lead to unsafe errors in Javascript

I am currently using AngularJS and encountering an issue when trying to call filePicker.pickAndStore from my Upload controller. Every attempt to use a filepicker.io API function triggers an "Unsafe Javascript attempt" error: The frame requesting access ...

Using CKEditor in an AngularJS web application: Tips and tricks

I'm having trouble integrating the ckeditor into an HTML page that's built with angularjs. Despite trying out numerous examples, such as the ng-ckeditor and ckeditor directives, I haven't found a solution that works for me. What I need is ...

What mechanism does the useState() function utilize in React to fetch the appropriate state object and function for a functional component when employing the state hook?

Currently focusing on deepening my understanding of the useState hook in react. I have a question regarding how useState retrieves the state object and modifier function specific to each functional component when it is called. What I'm wondering is w ...

Tips for getting a jQuery click event to function properly within an AngularJS application

Although I have some experience with jQuery and can write basic jQuery code, I am currently learning AngularJS. I have been following tutorials and studying sample code. Now, I want to practice some basic tasks in Angular that I could easily do with jQuer ...

Applying padding to an absolute div inside a Bootstrap 4 parent container does not function correctly

I'm trying to create a div with absolute position inside of another div with relative position using Bootstrap 4 like this: .p-r{ padding:8px; background-color:#ddd; height:100px; } .p-a{ bottom:3px; background-color:#000 } <link re ...

Organize your data with jQuery Tablesorter - Even works with columns spanning

Using Tablesorter with jQuery For my current project, I am utilizing Tablesorter from . Issue I have combined two column headers into one through merging / colspaning. This has resulted in the loss of sorting option for the third column. Example on jsF ...

Developing a sliding menu with AngularJS

Currently, I am developing an AngularJS application. One of the features I am working on involves having a menu at the top of my page that, when an item is selected, will slide down to reveal content specific to that selection in the same area as the menu. ...

Container for Magazines using HTML and CSS

Looking to develop a digital magazine application with smooth swipe transitions and fade in effects when swiping left and right. I attempted using jQuery.mobile, but struggled with adapting the background image height. My goal is to create a universal web ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

Issues with integrating WordPress into a subapp using AngularJS and web API in IIS?

I have developed an application in IIS and successfully configured my Wordpress site, mapping the URL as . Within that application, I created two sub-apps to publish my AngularJS app and web API. The URL of the app then became , but unfortunately, the log ...

Gathering information from mapped objects when they are clicked in a React application

Do you know how to retrieve genre.id when a user clicks on a Button and triggers the onClick function? Your assistance is greatly appreciated. ... return ( <div className="App"> <Header /> <div className="A ...