'How to display HTML content from API response on HTML page?
I sent a fetch request to an API which responded with:
<Game Gameid="12345">
<name primary="true">Apple</name>
<year>2011</year>
</Game>
Just wondering how I would display this data on my HTML page. I'm assuming I would need to process this with javascript or something.
Here is my current javascript:
fetch(url)
.then((response) => {
return response.json();
})
.then(data => {
console.log(data);
})
Just want the name and year displayed in a Div or something
Solution 1:[1]
Here is a small script demonstrating how to extract data from an XML string:
const xml=`<Game Gameid="12345">
<name primary="true">Apple</name>
<year>2011</year>
</Game>`;
const dom=(new DOMParser()).parseFromString(xml,"text/xml");
const game=dom.querySelector("*");
// console.log(game.tagName,game.getAttribute("Gameid"));
const data = [...game.children].reduce((a,t)=>(a[t.tagName]=t.textContent,a), {});
document.querySelector("div").textContent=`The name is ${data.name} and the year is ${data.year}.`;
<div></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
