Insert data from an Array into different HTML Divs - javascript

I have created 5 divs that have the same id and class with a loop. I'm now trying to populate each div with a different headline from the News API. I have managed to populate the first div with the data but I'm struggling how to insert data into the others.
Here is my attempt
// Fetch Data from API
fetch(req)
.then(r => r.json())
.then(r => {
const container = document.getElementsByClassName('postWrap')[0];
// Create div elements
for(i = 0; i < 5 ; i++) {
// Create title div
const titleDiv = document.createElement('div');
container.appendChild(titleDiv);
// Set ID & Class
titleDiv.id = 'postTitle';
titleDiv.classList.add('post-body');
// Post title data from array into div
let post = r.articles[i];
let title = post.title;
document.getElementById('postTitle').innerHTML = title;
}
});

The id of DOM should be unique. Same id of DOMs is not recommended.
Your div instances are created by your javascript code, so you can use those instance directly but get from ID.
const titleDiv = document.createElement('div');
/* Omitted.... */
// Post title data from array into div
let post = r.articles[i];
let title = post.title;
titleDiv.innerHTML = title;

Related

cant append text node to element using javascript

im trying to get some data from another html page and create an element in javascript and then added it to the dom
so far im trying to append a text node inside an h1 and p element from a variable
the console shows this error
script.js:32 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at script.js:32:7
this is the code i will add some comments to clarify :
window.addEventListener("load",() =>{
const data = (new URL (document.location)).searchParams;
// all of these are strings
const title = data.get('title');
const desc = data.get('desc');
const date = data.get("date");
const PDF = data.get("pdf");
// elmenet creation
const columns = document.createElement("div");
const worksheetCon=document.createElement("div");
const card = document.createElement("div");
const imageDiv = document.createElement("div");
const image = document.createElement("img");
const h1 = document.createElement("h1");
// creating h1 elment text node to append it later to h1 element
const h1Text = document.createTextNode(title);
const contain = document.createElement("div");
const p =document.createElement("p");
// creating p elment text node to append it later to append it later to p element
const Ptext = document.createTextNode(desc);
// trying to figure out type of text node it says its object
alert(typeof Ptext);
worksheetCon.className = "container-worksheets";
columns.className = "columns";
card.className = "carde";
imageDiv.className = "img";
contain.className = "contain";
worksheetCon.appendChild(columns);
columns.appendChild(card);
card.appendChild(imageDiv);
imageDiv.appendChild(image);
card.appendChild(h1);
h1.appendChild(h1Text)
card.appendChild(contain);
contain.appendChild(p);
p.appendChild(Ptext );
const worksheets = document.querySelector("worksheets");
worksheets.appendChild(card);
})
As I said, you never use Ptext, but you try to use desc as a Node
const desc = data.get('desc');
p.appendChild(desc);

Add url from HTMLCollection with Javascript

I'm trying to display images on click. Those images have urls that I get from an HTMLCollection. I need to add 2 divs containing different classes, I managed to do it but I can't get the url to display my images on click. Please can someone help me ?
const image = document.querySelector('.slider-image');
image.addEventListener("click", () => {
document.getElementById("modal").classList.remove('hidden')
// Get urls (display gallery items)
let urls = image.getElementsByClassName('gallery-url');
for (let i=0; i<urls.lenght; i++) {
const getDivSliderCtn = document.getElementsByClassName("slider-container");
let div = document.createElement('div');
div.classList.add('slider-image');
let bckgImage = div.style.backgroundImage=`url(${urls})`;
div.appendChild(bckgImage);
getDivSliderCtn +=urls[i];
}

Change text Inside heading with info from Array

I'm making a fetch call to retrieve some data on player cards.
I'm trying to display said cards and running into issues accurately parsing JSON and showing info in HTML.
Here is an example HTML heading for a card:
<h3 class="card__title">Example Card</h3>
Here is some JavaScript code I used after the fetch call:
let cardList = json.results
let cardTitle0 = cardList[0].name.toString();
How do I change the text from Example Card -> cardTitle0 from my array? This question applies to other attributes from the array and HTML objects.
You'll need to use the h3 element to get the link:
const link = document.querySelector(".card__title a");
// These can be const.
const cardList = json.results
const cardTitle0 = cardList[0].name.toString();
link.innerHTML = cardTitle0;
For multiple cards, you'd have to loop through the cardList json result and also through the elements on the page.
This is just an idea off the top of my head so I can't verify this code works or is even the best option for addressing multiple cards but hopefully it'll get you going in the right direction.
const links = document.querySelectorAll(".card__title a");
const cardList = json.results;
// Loop through the links on the page.
for (let i = 0; i < links.length - 1; i++)
{
for (let j = 0; j < cardList.length - 1; j++)
{
const title = cardList[j].name.toString();
links[i].innerHTML = title;
}
}

how when I add any new section in the index.html document, it will generate a new navigation item dynamically

const sections = Array.from(document.getElementsByTagName("section"));
for(section of sections){
const listItem = document.createElement('li');
navList.appendChild(listItem);
}
what i miss here
this is the task :
If you useHTML collection of all your sections getting them with their tag name like:
const sections = Array.from(document.getElementsByTagName("section"));
Then you can iterate over this array and generate separate elements.
This will make your code more dynamic as when you add any new section in the index.html document, it will generate a new navigation item dynamically.
I assume that you add your sections by coding rather dynamically. Based on that you can do this:
const generateList = () => {
let lis = [];
document.querySelectorAll('section').forEach(section => {
lis.push(`<li>${section.dataset.title}</li>`);
// change "section.dataset.title" according your dom element to grab text.
})
let ul = document.querySelector('ul');
ul.innerHTML = '';
ul.insertAdjacentHTML('afterbegin', lis.join(''));
}

Can't retrieve data from the NY Times API

I'm trying to get the largest image, title, short description and url of top stories from the NY Times API. Before I get all the information that I need, I'm trying to just get the titles but I can't seem to get any information appearing. Is something wrong with my code?
UPDATE: I've added the element to the DOM (please see code below) however the title still hasn't been displayed. I also tried printing it in the console before but nothing printed there either.
var url = 'https://api.nytimes.com/svc/topstories/v2/science.json?api-key=MY_API_KEY'
function setup() {
noCanvas()
loadJSON(url, gotData)
}
function gotData(data) {
const articles = data.results
for (let i = 0; i < articles.length; i++) {
const title = document.createElement('h1')
title.innerText = articles[i].title
document.body.appendChild(title)
}
}
Well, you created your element, but you still need to add it to the DOM.
To create your element:
const title = document.createElement('h1')
And to add it to the DOM (to make it actually appear on your page):
document.body.appendChild(title)
But now you still need to add your actual title from the API to it:
title.innerText = articles[i].title
And all together:
const title = document.createElement('h1') // create the heading
title.innerText = articles[i].title // add the title from the API to your heading
document.body.appendChild(title) // add your heading to the DOM (this will make it appear)
Have a look at this. I answered in your dupe but here is better
let html = [];
fetch('https://api.nytimes.com/svc/topstories/v2/science.json?api-key=yourApiKey')
.then((resp) => resp.json())
.then(function(data) {
data.results.forEach(res => {
html.push(`<h1>${res.title}</h1>`);
})
document.getElementById("res").innerHTML = html.join("");
})
<div id="res"></div>

Categories

Resources