"What is the process for concealing JSON data with the push of a button

I am looking to create two buttons - one for displaying JSON data (animals-1.json, animals-2.json, animals-3.json, etc. depending on the pageCounter which is working correctly) and a second button for deleting the first displayed JSON from the screen. Each JSON file contains only one number, for example, animals-1.json displays number 1, animals-2.json displays number 2, and so on... So, when the first button "SHOW" is clicked 3 times, it will display the numbers 1, 2, 3 on the screen. Then, when I click the second button "HIDE", I want the first number to disappear and only show numbers 2, 3 (from animals-2.json and animals-3.json). How can I achieve this? Thank you :)

<!DOCTYPE html>
<html>
<body>


<h2>next is</h2>
<button id="btn">SHOW</button>
<button id="btnn" >HIDE</button>
<div id="animal-info"></div>
<div id="nome"></div>
<script src="skripta.js"></script>

</body>
</html>

js:

 var pageCounter = 1;
   
    var animalContainer = document.getElementById("animal-info");
    
    var btn = document.getElementById("btn");
    var btnn = document.getElementById("btnn");
    
    btn.addEventListener("click", function(){
    
    var ourRequest = new XMLHttpRequest();
    ourRequest.open('GET', 'http://10.0.9.243/animals-' + pageCounter + '.json');
    ourRequest.onload = function(){
      var ourData = JSON.parse(ourRequest.responseText);
      renderHTML(ourData);
    };
    ourRequest.send();
    pageCounter++;
    });
    
    function renderHTML(data) {
    var htmlString = "";
    for (i = 0; i < data.length; i++){
      htmlString += "<p>" + data[i].name +  "</p>"
    }
    animalContainer.insertAdjacentHTML('beforeend', htmlString);
    
    
    }

Answer №1

The most effective method involves incorporating the class name into htmlString elements.

function renderHTML(data) {
var htmlString  = document.createElement("div");
for (i=0; i < data.length; i++){
  let pText = document.createTextNode(data[i].name);
  let pElement = document.createElement("p");
  pElement.append(pText);
  htmlString.append(pElement);
  htmlString.classList.add('containers') // new Line added
  }
animalContainer.append(htmlString);
}

btnn.addEventListener("click", function(){
let containers = document.getElementsByClassName('containers');
if(containers.length > 0){
    containers[0].remove();
}
  });

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

Applying styles to an active router-link in Vuejs: A step-by-step guide

I have a sidebar that contains multiple sidebar items like the following: <side-bar> <template slot="links"> <sidebar-item :link="{name: 'Home', icon: 'ni ni-shop text-primary', path: '/dashboard'} ...

What is the best way to correct the mouse position in relation to the canvas parent?

I am currently working on incorporating the Vuejs Draw Canvas from this Codepen example into my project as a component. The functionality is all working well, but I've noticed that the mouse position seems to be relative to the window. This causes iss ...

There seems to be an issue with the designated installation directory and it does not match wampserver

While attempting to install Wamp, I encountered an issue where the installation folder chosen was not that of Wampserver. No matter how many times I tried to change the folder, the error persisted. I even attempted installing the x86 version, but that didn ...

What is the best way to display an object in ReactJS?

My Object is: https://i.sstatic.net/QsQ1X.png I need to extract data from the recette-... endpoint in base64 format const articleList = Object.keys(this.state.users).map(key => { Object( this.state.users[key].recettes).map(data => { / ...

Refresh a single Object Key in React.js

Hey there, I'm currently working on updating book information via a PUT request to my API. My goal is to send only one property at a time, while keeping the rest unchanged. The issue I'm facing is that if I send just one property, the others are ...

Exploring the DOM, store all anchor elements inside a <ul> tag with a specific ID in an array

I'm attempting to extract all the anchor tags from a list and store them in an array by traversing the DOM. So far, I have been successful in getting the list items and their inner HTML into an array, but I am facing difficulties in retrieving each LI ...

Tips for utilizing document.write() with a document rather than just plain text

Currently, I am utilizing socket.io to develop a party game that shares similarities with cards against humanity. My main concern is how to retain the players' names and scores without needing to transmit all the data to a new page whenever new games ...

Understanding the grammar of the Web Speech API

Could someone please explain the meaning of this code snippet? const grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghost | white | g ...

Incorporating TypeScript basics into the if statement post compiling

As I delve into the Angular2 Quickstart, I stumbled upon a peculiar issue within app.component.js after compiling app.component.ts using tsc (version 1.8.2): if (d = decorators[i]) I am unable to pinpoint where I may have gone wrong in configuring the qu ...

Having trouble retrieving the selected value from a dropdown list with Jquery

In my current setup, I have a drop-down list situated within a pop-up modal. The dropdown menu is structured like this: <select name="EventTypeId" class="form-control formTextBox" id="ddlEventType"> <option value="">Please Select</optio ...

Prevent individual elements from shifting around on browser resizing within a React form

Having issues with a React form that includes an image gallery and input fields. import React, { Component } from 'react'; import ImageGallery from 'react-image-gallery'; import { Container, Row, Col, InputGroup, Button, FormControl, ...

Whenever attempting to utilize my login button in Swift, I often find myself having to press it twice in order for it to successfully connect with the mySQL

I'm in the process of developing an application that requires users to log in and register. When a user successfully registers, their account information is stored in my MySQL database. However, when I try to test the login feature, I encounter an iss ...

Redirecting visitors to a specific section of the website as soon as they enter the site

Currently, I am utilizing a jquery plugin known as Ascensor which can be found at this link: This plugin is designed for creating one-page websites with smooth scrolling capabilities both vertically and horizontally. It operates using a coordinate system ...

Tips for dealing with Uncaught Error: [nuxt] store/index.js must have a function that returns a Vuex instance

In my Nuxt project, I have set up a default store in Nuxt within the store/index.js file as per the guidelines provided in the documentation. However, upon trying to render my app, I encounter the following error: Uncaught Error: [nuxt] store/index.js sh ...

Removing only the final offspring within the main guardian with JSPlumb

I am currently working on a project involving objects arranged in a 4-by-X grid. To connect these objects, we are utilizing JS Plumb. However, we have encountered an issue where connecting "object 4" to "object 5" results in a diagonal line that crosses be ...

Using Javascript to toggle visibility of radio buttons on a PDF form

I've been looking around but haven't come across any information regarding using JavaScript with PDF form applications. If I missed something, I apologize and would appreciate any guidance. Currently, I have 5 radio buttons that are synchronized ...

Serialization of ExpandoObject using ServiceStack.Text

My current dilemma involves serializing objects using the library ServiceStack.Text. Interestingly, when I attempt to do this with a simple object, everything works perfectly: using System.Dynamic; using ServiceStack.Text; var x = new {Value= 10, Product ...

Searching in real-time with ajax in CodeIgniter framework is a seamless and efficient process

I'm a beginner in CodeIgniter and eager to learn. Currently, I'm facing an issue where the data is not being populated on the search page. In the model: function fetch_data($query) { $this->db->select('*'); $this-> ...

Disabling cookies disables Yii2 CSRF protection

I am encountering an issue with crsf verification in my AJAX requests on Yii2. Crsf is enabled in the config file 'request'=>array( 'enableCsrfValidation'=>true, 'enableCookieValidation'=>true, ) ...

Unattaching Events in AngularJS

I'm still navigating my way through the realms of Angular and MVC programming, uncertain if I'm on the right track. There's a jQuery snippet that I wish to implement in some of my partials, but not all. With event listeners that persist eve ...