Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
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 Respostas
Responde à pergunta

0

Pleas read here about replaceChild:

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda