I am trying to create a number of DOM item's using data from my firebase Firestore, however upon running, I have an error in line 34. I am just not quite sure what I should append resultGrid to, to achieve what I am looking for.
<div class="w-layout-grid grid">
<div class="result div-block">
<div class="data-image"></div>
<div class="result-footer">
<div class="results-text">
<h5 class="data-text">Taffy, 8 | Arabian</h5>
<h5 class="data-text">$12,000</h5>
This is my current javascript.
const resultList = document.querySelector('#horseList')
function renderResult(doc){
var resultGrid = document.createElement('div');
resultGrid.className = ('w-layout-grid grid');
var resultDiv = document.createElement('div');
resultDiv.className = ('result');
var resultImage = document.createElement('div');
resultImage.className = ('data-image');
var resultFooter = document.createElement('div');
resultFooter.className = ('result-footer');
var resultText = document.createElement('div');
resultText.className = ('results-text');
var resultButton = document.createElement('button');
resultButton.className = ('button tiny w-button');
resultButton.innerHTML = "View";
//Render text from database inside H5
const string = (`${doc.data().name}, ${doc.data().age} | ${doc.data().type}`);
let resultOne = document.createElement('h5');
let price = document.createElement('h5');
resultOne.className = ('data-text');
price.className = ('data-text');
price.textContent = (`$${doc.data().price}`);
resultOne.textContent = string;
resultList.appendChild(resultGrid);
resultGrid.appendChild(resultDiv);
resultDiv.appendChild(resultImage);
resultDiv.appendChild(resultFooter);
resultFooter.appendChild(resultText);
resultFooter.appendChild(resultButton);
resultText.appendChild(resultOne);
resultText.appendChild(price);
}
//connect to database & get data
const db = firebase.firestore();
db.collection("Horses").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
renderResult(doc);
});
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
Thanks in advance!
I figured it out! I ended up making the div GRID statically in HTML then I just set javascript to create the dynamic div's within that grid!
HTML
<div id="horseList" class="w-layout-grid grid"></div>
Javascript
const resultList = document.querySelector('#horseList')
function renderResult(doc){
var resultDiv = document.createElement('div');
resultDiv.className = ('result');
resultDiv.setAttribute('data-id', doc.id);
var resultImage = document.createElement('div');
resultImage.className = ('data-image');
var resultFooter = document.createElement('div');
resultFooter.className = ('result-footer');
var resultText = document.createElement('div');
resultText.className = ('results-text');
var resultButton = document.createElement('button');
resultButton.className = ('button tiny w-button');
resultButton.innerHTML = "View";
//Render text from database inside H5
const string = (`${doc.data().name}, ${doc.data().age} | ${doc.data().type}`);
let resultOne = document.createElement('h5');
let price = document.createElement('h5');
resultOne.className = ('data-text');
price.className = ('data-text');
price.textContent = (`$${doc.data().price}`);
resultOne.textContent = string;
resultList.appendChild(resultDiv);
resultDiv.appendChild(resultImage);
resultDiv.appendChild(resultFooter);
resultFooter.appendChild(resultText);
resultFooter.appendChild(resultButton);
resultText.appendChild(resultOne);
resultText.appendChild(price);
}
Related
No matter what I do, I'm unable to display my data. In my HTML I've set up this empty list:
<div class="reviews" style="margin-top: 40px;">
<ul id="reviews-list"></ul>
</div>
And this is what I have for JS:
// load
const querySnapshot = await getDocs(collection(db, "reviews"));
querySnapshot.forEach((doc) => {
createFormData(doc);
})
const formData = document.querySelector('.reviews');
function createFormData(doc) {
let div = document.createElement('DIV');
let title = document.createElement('span');
let hall = document.createElement('span');
let content = document.createElement('span');
title.textContent = doc.data().title;
hall.textContent = doc.data().hall;
content.textContent = doc.data().content;
div.appendChild(title);
div.appendChild(hall);
div.appendChild(content);
formData.appendChild(div);
}
Can anyone help?
I tried multiple Youtube videos and other sources to display my database data in a ul, and it either gives errors or nothing happens.
try this
const formData = document.querySelector('.reviews');
createFormData()
async function createFormData() {
const querySnapshot = await getDocs(collection(db, "reviews"));
querySnapshot.forEach((doc) => {
const div = document.createElement('DIV');
const title = document.createElement('span');
const hall = document.createElement('span');
const content = document.createElement('span');
title.textContent = doc.data().title;
hall.textContent = doc.data().hall;
content.textContent = doc.data().content;
div.appendChild(title);
div.appendChild(hall);
div.appendChild(content);
formData.appendChild(div);
})
}
I want to concatinate class name with variable count which keep getting updated after each button click, for which I am getting error as "citysName is null". can anyone suggest
button.addEventListener('click', resp => {
count = count +1;
var card = document.createElement('card');
card.innerHTML = `
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
**<h5 class="card_title" + count></h5>
<h6 class="temp" + count></h6>
<p class="card-text" + count></p>**
</div>
`;
card.className = 'card';
var content = document.getElementById('id1');
content.appendChild(card);
**var citysName = document.querySelector('.card_title'+count);
var description = document.querySelector('.card-text'+count);
var temp = document.querySelector('.temp'+count);**
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputVal.value+'&appid=a5599c020b0d897cbc8b52d547289acc')
.then(post => post.json())
.then(data => {
var cityName = data['name'];
var temper = data['main']['temp'];
var descrip = data['weather'][0]['description'];
let ctemp = Math.round(temper-273);
citysName.innerHTML = cityName;
temp.innerHTML = ctemp + "°C";
description.innerHTML = descrip;
})
})
First of all thats not how you add variables using template literals you can read more about it here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Second why do you query it again when you've just made the element you can use card as reference and if you need something within it, its much easier to access it using the variable you already have other than looking for it in your document
Maybe something like this but its hard to tell withouth more code etc
button.addEventListener('click', resp => {
count = count +1;
var card = document.createElement('card');
card.innerHTML = `
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
**<h5 class="card_title${count}"></h5>
<h6 class="temp${count}"></h6>
<p class="card-text${count}"></p>**
</div>
`;
card.className = 'card';
var content = document.getElementById('id1');
content.appendChild(card);
var citysName = card.querySelector('.card_title'+count);
var description = card.querySelector('.card-text'+count);
var temp = card.querySelector('.temp'+count);
fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputVal.value+'&appid=a5599c020b0d897cbc8b52d547289acc')
.then(post => post.json())
.then(data => {
var cityName = data['name'];
var temper = data['main']['temp'];
var descrip = data['weather'][0]['description'];
let ctemp = Math.round(temper-273);
citysName.innerHTML = cityName;
temp.innerHTML = ctemp + "°C";
description.innerHTML = descrip;
})
})
I'm having trouble implementing the logic that will limit me from adding the same items to my shopping list. When the item is the same, I just want to display the quantity with the existing item.
<div class="pizzas">
</div>
<div class="shoppingCart">
<p class="totalPrice">Hungry? order our pizzas</p>
</div>
// js
fetch("https://raw.githubusercontent.com/alexsimkovich/patronage/main/api/data.json")
.then(data => data.json())
.then(data => {
let valueCurrency = 0;
data.forEach(element => {
const shoppingCart = document.querySelector(".shoppingCart");
const pizzas = document.querySelector(".pizzas");
const box = document.createElement("div");
const img = document.createElement("img");
const title = document.createElement("h3");
const ingredients = document.createElement("p");
const price = document.createElement("h4");
const btn = document.createElement("button");
const totalPrice = document.querySelector(".totalPrice");
box.className = "box";
ingredients.className = "ingredients"
btn.className = "btn";
img.src = element.image;
img.className = "img";
title.innerHTML = element.title;
ingredients.innerHTML = element.ingredients;
price.innerHTML = element.price.toFixed(2) + " zł";
btn.innerHTML = "Dodaj do koszyka";
box.appendChild(img);
box.appendChild(title);
box.appendChild(ingredients);
box.appendChild(price);
box.appendChild(btn);
pizzas.appendChild(box);
btn.addEventListener("click", (e) => {
valueCurrency = valueCurrency + element.price;
const pizza = document.createElement("div");
pizza.className = "pizzaList";
const pizzasList = document.createElement("li");
const pizzaPrice = document.createElement("p");
const btnRemove = document.createElement("button");
btnRemove.innerText = "X";
pizzasList.innerText = title.textContent;
pizzaPrice.innerText = price.textContent;
pizza.appendChild(pizzasList);
pizza.appendChild(pizzaPrice);
pizza.appendChild(btnRemove);
totalPrice.innerText = "Całkowita cena: " + valueCurrency.toFixed(2);
if(pizzasList.innerText === pizzasList.innerText)
{
// don't add another item to the list
// just add +1 to existing element
}
else
{
// add an item to the list
shoppingCart.prepend(pizza);
}
btnRemove.addEventListener("click", (e) => {
pizza.remove();
valueCurrency = valueCurrency - element.price;
totalPrice.innerText = "Całkowita cena: " + valueCurrency.toFixed(2);
})
})
});
})
.catch(err => console.log(err));
My problem is exactly in the conditional statement, I don't know exactly how to implement the counting of the same pizzas option.
Thank you in advance for your help.
Since you are using html elements for this, what you can do is to use a data-attribute in your pizza element and increment it each time you need.
Something like:
if(pizzasList === pizzasList)
{
pizza.dataset.total = Number(pizza.dataset.total) + 1;
}
else
{
pizza.dataset.total = 1;
shoppingCart.prepend(pizza);
}
Then just use pizza.dataset.total to retieve the total number of repetitions.
I'm very new to javascript/dev so I hope there is a an obvious solution that I've not thought of. My code returns search items from TVMaze.com API. The feature giving me trouble is the incremental search (as a user types in input box, the code returns and displays images by creating a new div and appending images, removing and replacing the an div).
My problem is that on deleting all characters from input box, I receive the error: "Uncaught (in promise) TypeError: shows is not iterable" which I suppose means that there is no object to iterate over? Thanks in advance for any help.
const input = document.querySelector("#query");
input.addEventListener("input", async function (e) {
e.preventDefault();
const searchTerm = e.target.value;
const config = { params: { q: searchTerm } };
const res = await axios.get(`http://api.tvmaze.com/search/shows?`, config);
makeImages(res.data);
clearList();
});
const makeImages = (shows) => {
const div = document.createElement("div");
for (let result of shows) {
if (result.show.image) {
const img = document.createElement("IMG");
img.className += "resultImage";
img.src = result.show.image.medium;
const title = document.createElement("h3");
title.className += "resultTitle";
title.innerText = result.show.name;
const year = document.createElement("h4");
year.className += "score";
year.innerText = result.show.premiered;
var sub = year.innerText.substring(0, 4);
var yearNum = parseInt(sub);
div.append(year);
div.append(img);
div.append(title);
document.body.appendChild(div);
}
if (yearNum <= 2000) {
var retro = document.createElement("h5");
retro.className = "retro";
retro.innerText = "retro";
div.append(retro);
}
}
};
let clearList = () => {
var allImg = document.querySelectorAll("IMG");
if (allImg.length === 0) {
document.createElement("div");
return makeImages();
}
var oldDiv = document.querySelector("div");
oldDiv.remove();
console.log(oldDiv);
};
I am trying to convert an HTML Collection of "li"s into an array, but the result in the array being emptied.
I read this question and applied that, but it doesn't work.How do I convert a HTMLCollection into an array, without emptying it?
<body>
<ul id="base"></ul>
<script>
const json = [{
"id" : "1",
"date" : "2013/05/05",
},{
"id" : "2",
"date" : "2019/05/05",
}];
for (item of json) {
const list = document.createElement('li');
list.textContent = `${item.date}`;
base.appendChild(list)
}
///the code above works fine.
const base = document.getElementById("base");
const myNodeList = base.getElementsByTagName("li");
console.log(myNodeList);
// gives HTMLCollection
const myArray = Array.from(myNodeList)
// returns empty array
</script>
</body>
the result
I tested the same code on console and it worked fine as below.
The code cannot work before you are using base before initializing it. Placing the initialization before using it makes it work.
Here I modified it: https://jsfiddle.net/tk78z5gq/
Thank you so much guys!
The problem was async.
I should have said that earlier, I fetch the data from NeDB with async function.
The array was empty because DOM was executed before async function fetching data was executed.
The full code below was fixed one. I'm not sure this is best way, but at least it worked.
let dataM = null;
async function getHTMLData() {
const response = await fetch('/api');
const data = await response.json();
dataM = data;
const base = document.getElementById("base");
for (item of data) {
const root = document.createElement('li');
root.className = "col-md-auto";
root.title = `${item.date}`;
const border = document.createElement('div');
border.className = "row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative";
root.appendChild(border);
const flex = document.createElement('div');
flex.className = "col p-4 d-flex flex-column position-static";
border.appendChild(flex);
const country = document.createElement('strong');
country.className = "d-inline-block mb-2 text-primary";
const title = document.createElement('h3');
title.className = "mb-0";
const date = document.createElement('div');
date.className = "mb-1 text-muted";
date.id = "date";
const fieldItem = document.createElement('p');
fieldItem.className = "mb-auto";
const imageRoot = document.createElement('figure');
imageRoot.className = "image mb-2";
const link = document.createElement('a');
link.className = "p-4";
const linkText = document.createTextNode("Source");
country.textContent = `${item.country}`;
title.textContent = `${item.title}`;
date.textContent = `${item.date}`;
fieldItem.textContent = `${(item.fieldItem)}`;
for (var i = 0; i < item.imageSrc.length; i++) {
const image = document.createElement('img');
image.src = item.imageSrc[i];
image.alt = 'seized items'
image.className = "w-5 h-5";
// image.crossOrigin ="use-credentials";
imageRoot.appendChild(image);
}
const imageText = document.createElement('text');
imageText.innerHTML = `<br>${item.imageText}`;
imageRoot.appendChild(imageText);
link.appendChild(linkText);
link.title = "Source";
link.href = item.URL;
link.className = "";
flex.append(country, title, date, fieldItem, imageRoot, link);
base.appendChild(root);
}
}
sortDate();
async function sortDate() {
const gethtml = await getHTMLData();
const base = await document.getElementById("base");
const myNodeList = await base.getElementsByTagName("li");
const myArray = Array.from(myNodeList);
myArray.sort(function (a, b) {
return new Date(a.title) > new Date(b.title)? -1
: new Date(a.title) < new Date(b.title)? 1
: 0;
})
for (i = 0; i < myArray.length; i++) {
base.appendChild(base.removeChild(myArray[i]))}
}
index.js
app.get('/api', (request, response) => {
database.find({}).exec(function(err, data){
if (err) {
response.end();
return;
}
response.json(data);
})
});