I have a foreach loop that goes through all possible results of an API query
json.results.forEach(function(result) {
console.log(result.original_title);
document.getElementById("possibleResults").innerText = result.original_title;
}, this);
The console.log outputs all the elements correctly, however as expected, when I write to the possible results div, it only displays the last result.
How can I write my results to a div sequentially, so they are not overwritten, preferably without CSS?
Change document.getElementById("possibleResults").innerText = result.original_title;
to document.getElementById("possibleResults").innerText += result.original_title;
The first option replaces the current content of the div, that's why you only see the last result. The second one appends it to the end, keeping every result.
add all content after it is written in a variable.
var content;
json.results.forEach(function(result) {
console.log(result.original_title);
content += result.original_title;
}, this);
document.getElementById("possibleResults").innerText = content;
This is because
document.getElementById("possibleResults").innerText = result.original_title;
every next iteration will overwrite the text inserted by previous one.
Try with
json.results.forEach(function(result) {
console.log(result.original_title);
document.getElementById("possibleResults").innerText += result.original_title
}, this);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.