Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

241
Vistas
How to change picture in JavaScript on button click when using a mock JSON server?

I have a 'db.json' file and this file has data relating to images for the different Star Wars characters which was pulled from the Star Wars API.

I used this in my 'script.js':

function getPeople() {

let numberPeople = Math.floor((Math.random()*83)+1)
let apiUrl = 'https://swapi.dev/api/people/' +  numberPeople 

fetch(apiUrl)
.then(function(response){
    return response.json()
})
.then (function(json){
    console.log(json)
    let name = document.getElementById('name')
    let DOB = document.getElementById('DOB')
    let height = document.getElementById('height')
    let weight = document.getElementById('weight')
    let gender = document.getElementById('gender')

    name.innerText = `Name: ${json['name']}`;
    DOB.innerText = `Date of Brith: ${json['birth_year']}`;
    height.innerText = `Height: ${json['height']} cm`;
    weight.innerText = `Weight: ${json['mass']} kg`;
    gender.innerText = `Gender: ${json['gender']}`;

    
    fetch(`${json['homeworld']}`)
    .then(function(response) {
        return response.json()
    })
    .then(function(json) {
        console.log(json)
        let homeWorld = document.getElementById('home-world')

        homeWorld.innerText = `Home Planet: ${json['name']}`;
    })

fetch('./db.json')
        .then(results => results.json())
        .then(data => {
            console.log(data.people)

            var url = data.people[numberPeople-1]['imgUrl']
            var image = new Image();
            image.src = url

            
            document.getElementById('header').appendChild(image)

        })

The code in question start with "fetch('/db.json)" so the 'numberPeople' variable just pertains the id of the character. For example, Luke Skywalker, his url is https://swapi.dev/api/people/1, my webpage has randomised the number aspect so that on each click a new number is made getting a different character.

The mock JSON server (db.json) that was made has url's for pictures and via DOM manipulation depending on the 'numberPeople' variable will append the image depending on the character.

My problem is that when I click the button:

peopleButton.addEventListener('click', getPeople)

The pictures corresponds correctly with the character however, when I click it again the new picture is there as well as the previous picture. I tried different solutions but, I am not sure how to go about it when dealing with a JSON server.

Is there a way I can go about it? I am new to using JSON servers and any help would be great.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Pleas read here about replaceChild:

https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda