I have three similar functions that call JSON data from an API using HTML buttons, and change it to a string using stringify. The results display in a div, and each new call adds to the current browser page, making it longer. I would like to have each new call replace any previous data displayed in the page.
If I understand correctly, I can't use ReplaceChild once the JSON is stringified. I have tried using string.replace(), but perhaps I am using it incorrectly.
Here is the working code I'm trying to build on:
<body>
<button onclick="awardees()">View NDNP Awardees</button>
<button onclick="ocrFeed()">View Recently-Added OCR'd Pages</button>
<button onclick="batches()">View Available Batches</button>
<script>
function awardees(){
fetch('https://chroniclingamerica.loc.gov/awardees.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var string = JSON.stringify(myJson);
document.getElementById('results').innerHTML += "<br/>"+string;
});
}
function ocrFeed(){
fetch('https://chroniclingamerica.loc.gov/ocr.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var string = JSON.stringify(myJson);
document.getElementById('results').innerHTML += "<br/>"+string;
});
}
function batches(){
fetch('https://chroniclingamerica.loc.gov/batches.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var string = JSON.stringify(myJson);
document.getElementById('results').innerHTML += "<br/>"+string;
});
}
</script>
<div id ="ticket">
<span id="results"></span>
</div>
</body>
</html>
Where would I need to add additional lines, and what method do you think would be best?
Thank you so much!
If I understand correctly, you should only replace
document.getElementById('results').innerHTML += "<br/>"+string; by document.getElementById('results').innerHTML = "<br/>"+string; and you will replace the div content with new string instead of adding it to the existent one.