Reputation: 11
Console.log(data[i].title) displays the correct output but when I try to display it using innerHTML only one result is returned.
I am new to coding and I am working on a web-scrapper project. I have a server running that grabs the headlines of NBC news and inputs the data into an array. When I try to display the data on my frontend using console.log it returns the right results but when I try to display the results on my html page it just returns the final result. The results are shown in the attached image.
<!DOCTYPE html>
<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>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="list"></div>
<input type="text" id="input"></input><br>
<button id="submit" type="submit">Submit</button><br><br>
<p id="p"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>
const PORT= 8000;
const axios = require('axios')
const cheerio = require('cheerio');
const express = require('express')
const cors= require('cors');
const { html } = require('cheerio/lib/static');
// to run this use 'npm run start' in the terminal
const url = 'https://www.nbcnews.com/';
const app = express();
app.use(cors())
app.get('/results', (req, res) => {
axios(url)
//var x = req.body.input
.then(response=> {
const article= []
const html=response.data;
const $=cheerio.load(html);
$('.alacarte__headline', html).each(function(){
const title= $(this).text()
//._13svhQIUZqD9PVzFcLwOKT styled-outbound-link
article.push({
title
})
})
res.json(article)
}).catch(err => console.log(err))
})
app.listen(PORT, () => console.log(`listening on port ${PORT}`))
const feedDisplay= document.querySelector('#list');
fetch('http://localhost:8000/results')
.then(response => {
return response.json()
})
.then(data=> {
var x= ''
for(i=0; i<data.length; i++) {
console.log(data[i].title)
document.getElementById("p").innerHTML=(data[i].title)
}
Upvotes: 0
Views: 292
Reputation: 631
Here:
document.getElementById("p").innerHTML=(data[i].title)
you are setting new value of innerHTML
. This replaces previous value.
You can use array map method to get list of all titles and then join them using array join method.
I used ' '
space as separator, but you can replace it with any string.
const feedDisplay= document.querySelector('#list');
fetch('http://localhost:8000/results')
.then(response => {
return response.json()
})
.then(data => {
document.getElementById("p").innerHTML = data.map(d => d.title).join(' ')
}
Upvotes: 1