I am trying to make a pokemon team generator with pokeapi and i am able to fetch the text info fine but i cant figure out a way to display the image.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Java Script 201</title>
</head>
<body>
<img src="" id="monster">
<h3>Name:</h3>
<div id="name"></div>
<h3>Height:</h3>
<div id="height"></div>
<h3>Weight:</h3>
<div id="weight"></div>
<button class="button">Generate Pokemon Team!</button>
<script src="script.js"></script>
</body>
</html>
const name = document.getElementById("name");
const pokemonImage = document.getElementById('pokemon')
const height = document.getElementById("height");
const weight = document.getElementById("weight");
const button = document.querySelector(".button");
button.addEventListener('click', (e) => {
e.preventDefault()
const randomNumber = Math.ceil (Math.random() * 905)
fetch (`https://pokeapi.co/api/v2/pokemon/${randomNumber}/`)
.then (response => response.json())
.then (pokemon => {
console.log(pokemon)
name.innerHTML = pokemon ['name'];
height.innerHTML = pokemon ['height'];
weight.innerHTML = pokemon ['weight'];
id.innerHTML = (`Pokemon Id: ${Pokemon['id']}`);
pokemonImage.innerHTML =`<img id='monster' src=https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${Pokemon['id']}.png>`
})
})
I have tried using ID and just cant seem to find a good anwsxer on the internet.
You can just get the tag wit the id and set the attribute
const nameElem = document.getElementById("name");
const pokemonImage = document.getElementById('pokemon')
const heightElem = document.getElementById("height");
const weightElem = document.getElementById("weight");
const button = document.querySelector(".button");
button.addEventListener('click', (e) => {
e.preventDefault()
const randomNumber = Math.ceil(Math.random() * 905)
fetch(`https://pokeapi.co/api/v2/pokemon/${randomNumber}/`)
.then(response => response.json())
.then(pokemon => {
const {
name,
height,
weight,
sprites
} = pokemon;
console.log(name)
nameElem.innerHTML = name;
heightElem.innerHTML = height;
weightElem.innerHTML = weight;
pokemonImage.setAttribute('src', sprites.back_default);
})
})
<img src="" id="pokemon">
<h3>Name:</h3>
<div id="name"></div>
<h3>Height:</h3>
<div id="height"></div>
<h3>Weight:</h3>
<div id="weight"></div>
<button class="button">Generate Pokemon Team!</button>