How to get child of div in cheerio - javascript

I am working with cheerio and I am stuck at a point where I want to get the href value of children div of <div class="card">.
<div class="Card">
<div class="title">
<a target="_blank" href="test">
Php </a>
</div>
<div>some content</div>
<div>some content</div>
<div>some content</div>
</div>
I got first childern correctly but i want to get div class=title childern a href value. I am new to node and i already search for that but i didn't get an appropriate answer.
var jobs = $("div.jobsearch-SerpJobCard",html);
here is my script
const rp = require('request-promise');
const $ = require('cheerio');
const potusParse = require('./potusParser');
const url = "";
rp(url)
.then((html)=>{
const Urls = [];
var jobs = $("div.Card",html);
for (let i = 2; i < jobs.length; i++) {
Urls.push(
$("div.Card > div[class='title'] >a", html)[i].attribs.href
);
}
console.log(Urls);
})
.catch(err => console.log(err));

It looks something like this:
$('.Card').map((i, card) => {
return {
link: $(card).find('a').text(),
href: $(card).find('a').attr('href'),
}
}).get()
Edit: the nlp library is chrono-node and I also recommend timeago.js to go the opposite way

Related

window.onload doesn't run the whole function (javascript)

I tried to make this function getWeekly() run by default when the site first loads but it only runs this part of the code:
dailyBtn.classList.add("active");
weeklyBtn.classList.remove("active");
monthlyBtn.classList.remove("active");
but not the loop under. But it'll show data when I click on the tags. Any ideas? Thanks.
Git link: https://github.com/thusmiley/time-tracking-dashboard.git
Live site link: https://thusmiley.github.io/time-tracking-dashboard
index.html
<div class="report-bottom">
Daily
Weekly
Monthly
</div>
</div>
<div class="stat-wrapper">
<div class="work-bg bg"></div>
<div class="stat" id="work">
<div class="category">
<h2>Work</h2>
<img src="./images/icon-ellipsis.svg" alt="" />
</div>
<div class="card">
<h3 class="work-current"></h3>
<p class="work-previous"></p>
</div>
</div>
</div>
script.js
let Data = [];
fetch("./data.json")
.then((response) => response.json())
.then((data) => Data.push(...data));
let card = document.querySelectorAll(".card");
let dailyBtn = document.getElementById("daily");
let weeklyBtn = document.getElementById("weekly");
let monthlyBtn = document.getElementById("monthly");
function getDaily() {... }
function getWeekly() {
dailyBtn.classList.remove("active");
weeklyBtn.classList.add("active");
monthlyBtn.classList.remove("active");
for (let i = 0; i < Data.length; i++) {
let splitTitle = Data[i].title.split("");
splitTitle = splitTitle.filter((e) => String(e).trim());
let joinTitle = splitTitle.join("");
let current = document.querySelector(`.${joinTitle.toLowerCase()}-current`);
let previous = document.querySelector(
`.${joinTitle.toLowerCase()}-previous`
);
current.innerHTML = `${Data[i].timeframes.weekly.current + "hrs"}`;
previous.innerHTML = `${
"Last Week - " + Data[i].timeframes.weekly.previous + "hrs"
}`;
}
}
function getMonthly() {... }
window.onload = getWeekly();
The very first time that you load the page Data.length is equal to 0, and that's why the loop doesn't iterate. You are using an asynchronous call to load Data, and when getWeekly() is called for the first time, Data is not ready with the info yet (and it only works after when its ready).
You should wait until Data is completely load first, you can try a callback function or even try $.when() using jquery.

Assign looped img url to div

Attempting to recreate a Netflix app in HTML, CSS and JS to support my learning and become more proficient at JS. I want to give each div a background image from an object. The object contains 20 or so images of which I have looped through to get each respective url.
const getMovies = () => {
const movieEndpoint = '/discover/movie';
const requestParams = `?api_key=${tmdbKey}`;
const urlToFetch = `${tmdbBaseUrl}${movieEndpoint}${requestParams}`;
fetch(urlToFetch)
.then(response => {
return response.json();
})
.catch(error => {
console.log(error)
})
.then(data => {
const jsonResponse = data;
movies = jsonResponse.results;
console.log(movies);
for (const movie of movies) {
const fullSource = `https://image.tmdb.org/t/p/original/${movie.backdrop_path}`;
console.log(fullSource);
}
})
};
This successfully logs each url to the console, the trouble I have now is assigning them as backgrounds to existing div elements I have in a similar fashion. I have attempted to write a for loop to go through the divs and then change the background using style.backgroundImage = url(${fullSource}) but this doesn't work for me.
HTML looks like this:
<div id="category">
<div class="film"></div>
<div class="film"></div>
<div class="film"></div>
<div class="film"></div>
<div class="film"></div>
<div class="film"></div>
<div class="film"></div>
<div class="film"></div>
<div class="film"></div>
<div class="film"></div>
<div class="film"></div>
<div class="film"></div>
</div>
I have styled the divs in css haven't been able to find a successful method to assign the backgrounds.
To be clear, I would like to populate the divs with a random image from the object using the urls that have been populated.
Any help is appreciated!
const data = [
{
image: 'https://i.picsum.photos/id/1036/200/300.jpg?hmac=VF4u-vITiP0ezQiSbE3UBvxHDFf8ZqJDycaAIoffsCg'
},
{
image: 'https://i.picsum.photos/id/106/200/300.jpg?hmac=qnjqfh7hXrQF9MAA1T3JOgK3dhnLfxOo-HkzhyZoB2g'
},
{
image: 'https://i.picsum.photos/id/1036/200/300.jpg?hmac=VF4u-vITiP0ezQiSbE3UBvxHDFf8ZqJDycaAIoffsCg'
}
]
for (let index = 0; index < data.length; index++) {
const element = document.getElementById(`category-${index}`);
element.style.backgroundImage = `url(${data[index].image})`;
element.style.backgroundRepeat = 'no-repeat';
element.style.backgroundColor = "#f3f3f3";
element.style.backgroundSize = 'auto';
// element.style.backgroundPosition = '100vh 100vh';
element.style.width= '100%';
element.style.height = '100vh'
}
<div style="display: flex;">
<div id="category-0">Background Image 1</div>
<div id="category-1">Background Image 2</div>
<div id="category-2">Background Image 3</div>
</div>

How can I interpret my JSON via Google Books API URL and display it on my HTML page using JS?

So, I am trying to pull the volume info from the JSON array from the URL provided: https://www.googleapis.com/books/v1/volumes?q=HTML5
Trying to pull author, title, images, page numbers and description.
This specific class of my HTML code I want to put the JSON data that I have mentioned above in is the 'b-card' class:
<div class="booklist">
<div class="booklist-cards">
<div class="b-card">
</div>
<div class="b-card">
</div>
<div class="b-card">
</div>
<div class="b-card">
</div>
<div class="b-card">
</div>
<div class="b-card">
</div>
<div class="b-card">
</div>
<div class="b-card">
</div>
</div>
</div>
<script src="https://www.googleapis.com/books/v1/volumes?q=HTML5"></script>
<script src="assets/js/script.js"></script>
The script.js file I have tried is below:
function handleResponse(obj) {
const book = Objects.keys(obj).map(item => obj['items']).reduce(
(acc, rec, id, array) => {
let singleBookCover = rec[id].volumeInfo.imageLinks.thumbnail;
let singleBookTitle = rec[id].volumeInfo.title;
let singleBookAuthor = rec[id].volumeInfo.authors[0];
return [...acc, {singleBookCover, singleBookTitle, singleBookAuthor}]
},
[]
).forEach( item => {
let title = document.createElement('h1');
title.textContent = `${item.singleBookTitle}`;
let author = document.createElement('strong');
author.textContent = `${item.singleBookAuthor}`;
let img = document.createElement('img');
img.src = item.singleBookCover;
img.alt = `${item.singleTitle} by ${item.singleBookAuthor}`;
let container = document.getElementsByClassName('b-card');
container.appendChild(title).appendChild(author).appendChild(img);
})
return book
}
The above code only adds the title image and author, but I cant get them to load into my HTML.
What are ways to resolve this? Am i calling the URL correctly in the HTML script tag?
Forgot to mention - would like to achieve this without using JQuery & AJAX. I have also tried inputting the callback to handleResponse in the script tag url but it doesnt work.
you can't append to the HTML because container is array so it need index of the element
container[index].appendChild(title).appendChild(author).appendChild(img);
but here simple version, and don't forget to add &callback=handleRespons to the API URL
function handleResponse(obj) {
obj.items.forEach((item, index) => {
if(index > 7) return; // limit 8 result
let div = document.createElement('div');
div.className = 'b-card';
div.innerHTML = `<h1>${item.volumeInfo.title}</h1>
<p><strong>${item.volumeInfo.authors[0]}</strong></p>
<img src="${item.volumeInfo.imageLinks.thumbnail}" alt="${item.singleTitle} by ${item.volumeInfo.authors[0]}" />`
let container = document.querySelector('.booklist-cards');
container.append(div);
})
}
<div class="booklist">
<div class="booklist-cards">
</div>
</div>
<script src="//www.googleapis.com/books/v1/volumes?q=HTML5&callback=handleResponse" async></script>

How do I use For Loop in JavaScript to show the list?

I am a beginner in JavaScript and I can't figure out the following problem: I am trying to create a simple JavaScript Movie List. I have 10 lists on the Movie List. I tried to show all of the lists with for loop, but it doesn't work.
Here's the code:
function renderModal() {
for (let i = 0; i < listMovies.length; i++) {
let movieData = listMovies[i];
document.getElementById("poster").src = movieData.img;
document.getElementById("title").innerHTML = movieData.name;
document.getElementById("genre").innerHTML = movieData.genre;
document.getElementById("rating-num").innerHTML = "Rating: "+ movieData.rating + "/10";
document.getElementById("movie-desc").innerHTML = movieData.desc;
document.getElementById("imdb-page").href = movieData.link;
return movieData;
}
}
What do I have to do?
Help me to fix it!.
You can use template tag for list and render it into target element.I am showing an example.
Movie list
<div id="movieList"></div>
template for list
<template id="movieListTemplate">
<div class="movie">
<img src="" class="poster" alt="">
<div class="title"></div>
<div class="genre"></div>
<div class="rating-num"></div>
<div class="movie-desc"></div>
<div class="imdb-page"></div>
</div>
</template>
Javascript code:
if (listMovies.length > 0) {
const movileListTemplate = document.getElementById('movieListTemplate')
const movieRenederElement = document.getElementById('movieList')
for(const movie of listMovies) {
const movieEl = document.importNode(movileListTemplate.content, true)
movieEl.querySelector('.poster').src = movie.img
movieEl.querySelector('.title').textContent = movie.name
//use all queryselector like above
}
}
Your return movieData; will stop the loop dead. Not that running it more than once will change anything since you change the same elements over and over. IDs must be unique.
Here is a useful way to render an array
document.getElementById("container").innerHTML = listMovies.map(movieData => `<img src="${movieData.img}" />
<h3>${movieData.name}</h3>
<p>${movieData.genre}</p>
<p>Rating: ${movieData.rating}/10</p>
<p>${movieData.desc}
IMDB
</p>`).join("<hr/>");
With return movieData, the for loop will ends in advance.You should put it outside the for loop.

Json file struggling with the length

So, i got everything almost working as i want it, just a mistake that im struggling. Everytime i search for an item, when the result for that item shows the length is repeated.
When i search for ox there are 2 results and that is correct, but the length (2) shows in both of them, i only display one
[Code]
const resultHtml = (itemsMatch) => {
if (itemsMatch.length > 0) {
const html = itemsMatch
.map(
(item) => `
<span>${itemsMatch.length}</span>
<div class="card">
<div class="items-img">
</div>
<div class="items-info">
<h4>${item.title}</h4>
<small>${item.path}</small>
</div>
</div>
`
)
.join('');
//console.log(html);
itemList.innerHTML = html;
}
};
////
Question 2
I got one more question, i was trying to get the image from the Json and what i got was the path haha
why the apth and not the img
const resultHtml = (itemsMatch) => {
if (itemsMatch.length > 0) {
const html =
`<span class="items-results">${itemsMatch.length} Resultados</span>` +
itemsMatch
.map(
(item) => `
<div class="card">
<div class="items-img">
${item.image}
</div>
<div class="items-info">
<h4>${item.title}</h4>
<small>${item.path}</small>
</div>
</div>
`
)
.join('');
console.log(html);
itemList.innerHTML = html;
}
};
If you move <span>${itemsMatch.length}</span> out of your map callback, it will not repeat for each item. Read more about map() here.
Replace:
const html = itemsMatch
.map(
(item) => `
<span>${itemsMatch.length}</span>
... more HTML here
`
)
.join('');
With this:
const html = `<span>${itemsMatch.length}</span>` + (
itemsMatch
.map(
(item) => `
<div class="card">
<div class="items-img">
</div>
<div class="items-info">
<h4>${item.title}</h4>
<small>${item.path}</small>
</div>
</div>
`
)
.join('')
);
Regarding your image issue:
You are just outputting the path and that's why it's printing out just the path. If you are trying to display an image then put the path as source of <img> tag.
So, instead of just:
${item.image}
Use:
<img src="${item.image}">

Categories