const searchButton = document.getElementById("search-button");
const searchInput = document.getElementById("search-input");
const fields = {
name: document.getElementById("creature-name"),
id: document.getElementById("creature-id"),
weight: document.getElementById("weight"),
height: document.getElementById("height"),
types: document.getElementById("types"),
hp: document.getElementById("hp"),
attack: document.getElementById("attack"),
defense: document.getElementById("defense"),
specialAttack: document.getElementById("special-attack"),
specialDefense: document.getElementById("special-defense"),
speed: document.getElementById("speed")
};
searchButton.addEventListener("click", async () => {
const query = searchInput.value.trim().toLowerCase();
if (!query) return;
try {
const res = await fetch(`https://rpg-creature-api.freecodecamp.rocks/api/creature/${query}`);
if (!res.ok) throw new Error("Creature not found");
const data = await res.json();
console.log("API Response:", JSON.stringify(data, null, 2)); // Debug output
// Clear types before adding new ones
fields.types.innerHTML = "";
// Fill in basic fields
fields.name.textContent = data.name?.toUpperCase() || "";
fields.id.textContent = data.id ? `#${data.id}` : "";
fields.weight.textContent = data.weight ? `Weight: ${data.weight}` : "";
fields.height.textContent = data.height ? `Height: ${data.height}` : "";
// Extract stats explicitly
const getStat = (name) => {
if (!Array.isArray(data.stats)) return "";
const statObj = data.stats.find(s => s.stat && s.stat.name === name);
return statObj ? statObj.base_stat : "";
};
fields.hp.textContent = getStat("hp");
fields.attack.textContent = getStat("attack");
fields.defense.textContent = getStat("defense");
fields.specialAttack.textContent = getStat("special-attack");
fields.specialDefense.textContent = getStat("special-defense");
fields.speed.textContent = getStat("speed");
// Add type elements
if (Array.isArray(data.types)) {
data.types.forEach(typeObj => {
const typeName = typeObj?.type?.name?.toUpperCase();
if (typeName) {
const typeEl = document.createElement("span");
typeEl.textContent = typeName;
fields.types.appendChild(typeEl);
}
});
}
} catch (err) {
alert("Creature not found");
}
});
```
Please do not create duplicate topics for the same challenge/project question(s). If you need more help then respond back to the original topic you created with your follow up questions and/or your updated code and question.
This duplicate topic has been unlisted.
Thank you.
A post was merged into an existing topic: Help me with the failed steps in my javaScript code