forEach loop keeps appending to first child element only - javascript

I'm in a bit of a pickle. I'm running a forEach loop for an API that will create a new div for each result with some html appended inside it. While the data is being retrieved, it appends only to the first div created. I'm trying to ensure each set of text ends up in each individual div. Can anyone enlighten me on what I'm doing wrong? Thanks
app.displayResults = (arrayOfObjects) => {
arrayOfObjects.forEach((Object) =>{
const number = Object.house_number;
const address = Object.street_name;
const zipCode = Object.zip_code;
const borough = Object.borough;
const date = Object.inspection_date;
const initial = Object.inspection_type;
const iResult = Object.result;
const resultContainer = document.createElement("div");
resultContainer.classList.add('resultContainer');
document.querySelector('.inspectionResults').append(resultContainer);
const innerHTML = `
<p class = "recordDetails"> ADDRESS: ${number}${address}</p>
<p class = "recordDetails"> DATE: ${date}</p>
<p class = "recordDetails"> BOROUGH: ${borough}</p>`
const record = document.createElement("div");
record.classList.add('record');
record.innerHTML = `${innerHTML}`
document.querySelector(".resultContainer").append(record)
})
}

In the last line of your forEach callback, you're querying the first .resultContainer element instead of the one you've created before. Instead of immediately appending that div to the DOM, append your record to resultContainer, then append only resultContainer to the DOM, like this (I've changed Object to obj because Object is already defined):
app.displayResults = (arrayOfObjects) => {
arrayOfObjects.forEach((obj) =>{
const number = obj.house_number;
const address = obj.street_name;
const zipCode = obj.zip_code;
const borough = obj.borough;
const date = obj.inspection_date;
const initial = obj.inspection_type;
const iResult = obj.result;
const resultContainer = document.createElement("div");
resultContainer.classList.add('resultContainer');
const innerHTML = `
<p class = "recordDetails"> ADDRESS: ${number}${address}</p>
<p class = "recordDetails"> DATE: ${date}</p>
<p class = "recordDetails"> BOROUGH: ${borough}</p>`
const record = document.createElement("div");
record.classList.add('record');
record.innerHTML = `${innerHTML}`
resultContainer.appendChild(record); // instead of directly appending record to document append it to the container, then append the container to the document
document.querySelector('.inspectionResults').append(resultContainer);
})
}

app.displayResults = (arrayOfObjects) => {
arrayOfObjects.forEach((obj) =>{
/*
const number = Object.house_number;
const address = Object.street_name;
const zipCode = Object.zip_code;
const borough = Object.borough;
const date = Object.inspection_date;
const initial = Object.inspection_type;
const iResult = Object.result;
*/
// Destructuring Assignment maybe better here
const { house_number : number,
street_name : address,
zip_code : zipCode,
borough,
inspection_date : date,
inspection_type : initial,
result : iResult } = obj
const resultContainer = document.createElement("div");
resultContainer.classList.add('resultContainer');
// below is the problem, you appended several divs with the class name 'resultContainer', every time you query, there were a array of it, and you always got the first.
// document.querySelector('.inspectionResults').append(resultContainer);
const innerHTML = `
<p class = "recordDetails"> ADDRESS: ${number}${address}</p>
<p class = "recordDetails"> DATE: ${date}</p>
<p class = "recordDetails"> BOROUGH: ${borough}</p>`
const record = document.createElement("div");
record.classList.add('record');
record.innerHTML = innerHTML
// here just append to the exact div you created above
resultContainer.append(record)
// then append the container which contains the content you expected to the documment
document.querySelector('.inspectionResults').append(resultContainer);
})
}

How about adding an identifier?
terms.setAttribute(‘id’,‘para-1’);

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);

How can I add multiple data to <li>? [duplicate]

This question already has answers here:
Creating a new DOM element from an HTML string using built-in DOM methods or Prototype
(29 answers)
Closed last year.
function addUserDataToDom(data) {
const li = document.createElement('li')
const userList = document.getElementById('user-list')
const userName = data.items[0].login
const id = data.items[0].id
const avatarUrl = data.items[0].avatar_url
li.innerHTML = userName
}
I have to add my id and avatarUrl to <li> and append to the page? Thank you
You can add any element to another one with .appendChild( childElement ). So if you want to add the "li" to the body of your document you can do this:
document.body.appendChild( li )
So, in order to achieve what you asked, you should make this:
function addUserDataToDom(data) {
const li = document.createElement('li')
const userList = document.getElementById('user-list')
const userName = data.items[0].login
const id = data.items[0].id
const avatarUrl = data.items[0].avatar_url
// Create p elements to add your user data
const pUserName = document.createElement("p")
const pId = document.createElement("p")
const pAvatrUrl = document.createElement("p")
pUserName.innerText = userName
pId.innerText = id
pAvatrUrl.innerText = avatarUrl
li.appendChild( pUserName )
li.appendChild( pId )
li.appendChild( pAvatrUrl )
}
As you can see, all the data was added as innerText inside the p element.
Finally you have to append those p elements we created earlier inside your li element.

Combining textContent into one header when rendering Javascript

Very new to javascript here, just two days in, but I have decided to start a pretty ambitious project using Javascript and Firebase.
Below I am trying to render the Javascript from Firestore to HTML, but as you can probably see, it's creating 4 H5's. Ideally, I have all the text inside of one H5, but formatted nicely.
Here is my javascript (again I just started learning this two days ago so I am very new)
const resultList = document.querySelector('#horseList')
function renderResult(doc){
let li = document.createElement('li');
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";
let name = document.createElement ('h5');
name.className = ('data-text');
let age = document.createElement ('h5');
age.className = ('data-text');
let type = document.createElement ('h5');
type.className = ('data-text');
let price = document.createElement ('h5');
price.className = ('data-text');
li.setAttribute('data-id', doc.id);
name.textContent = doc.data().name;
age.textContent = doc.data().age;
type.textContent = doc.data().type;
price.textContent = doc.data().price;
resultList.appendChild(li);
li.appendChild(resultDiv);
resultDiv.appendChild(resultImage);
resultDiv.appendChild(resultFooter);
resultFooter.appendChild(resultText);
resultFooter.appendChild(resultButton);
resultText.appendChild(name);
resultText.appendChild(type);
resultText.appendChild(age);
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);
});
And here is what I am hoping to achieve in HTML
<ul id="horseList" role="list" class="result-list">
<li>
<div class="result">
<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>
</div>View</div>
Updated code:
let lineone = document.createElement ('h5');
lineone.className = ('data-text');
let linetwo = document.createElement ('h5');
linetwo.className = ('data-text');
li.setAttribute('data-id', doc.id);
lineone.textContent = ${doc.data().name}, ${doc.data().age}, ${doc.data().type};
linetwo.textContent = ${doc.data().price};
Any help would be great! Thanks!
You can combine all the data calls into a single string variable using template literals, and then set that variable to the text content of your h5 element:
const string = `${doc.data().name}, ${doc.data().age} | ${doc.data().type}`;
let h5 = document.createElement('h5');
h5.textContent = string;
how are you? you can try to use the template literals, creating just one h5 for the 3 attributes name, age, type:
phrase.textContent = ${doc.data().name}, ${doc.data().age} ${doc.data().type}

How to create HTML element for JavaScript and not for HTML

I have this simplified code:
const chancesData = ["facebook","twitter","google"];
let inputsArr = [];
const inputsArrFill = chancesData.map((cur, index) => {
const input = (document.createElement("input").value =
chancesData[index]);
inputsArr.push(input); //I want the pushed value to be something like this "<input value"facebook">"
return inputsArr;
//so the returned array (should) be something like this:
//["<input value"facebook">","<input value"twitter">","<input value"google">"]
});
console.dir(inputsArrFill);
as you can see if you opened this coed in your console, the returned array looks like this:
['facebook', 'twiiter', 'google']
I want it to look like this:
['<input value="facebook">','<input value="twitter">','<input value="google">']
You can use setAttribute to put the value into the HTML markup, then retrieve it with outerHTML:
const chancesData = ["facebook", "twitter", "google"];
const inputsArrFill = chancesData.map(str => {
const input = document.createElement("input");
input.setAttribute('value', str);
return input.outerHTML;
});
console.dir(inputsArrFill);
But it'd be easier to use ordinary string concatenation:
const chancesData = ["facebook", "twitter", "google"];
const inputsArrFill = chancesData.map(str => `<input value="${str}">`);
console.dir(inputsArrFill);
The result of an assignment expression, is the assigned value. With
const input = (document.createElement("input").value =
chancesData[index]);
you did not store a reference to the created HTML element into your variable, you stored the assigned value, chancesData[index].
You need to do these two things in separate steps.
const chancesData = ["facebook","twitter","google"];
let inputsArr = [];
const inputsArrFill = chancesData.map((cur, index) => {
const input = document.createElement("input");
input.value = chancesData[index];
inputsArr.push(input); //I want the pushed value to be something like this "<input value"facebook">"
return inputsArr;
//so the returned array (should) be something like this:
//["<input value"facebook">","<input value"twitter">","<input value"google">"]
});
console.dir(inputsArrFill);
But if you really want <input value="facebook"> as a result, then you will probably have to push that in string form to begin with. You have little control over how an HTML element object gets displayed by the console.
Please refer below code.
(function createHTMlString() {
const chancesData = ["facebook", "twitter", "google"];
var outputObj = []
for (var i = 0; i < chancesData.length; i++) {
var inputTag = document.createElement("INPUT");
inputTag.setAttribute("value", chancesData[i]);
outputObj.push(inputTag);
}
console.log(outputObj)
})();

Best way to pass some variable/id through google cloud functions child?

How to get this running ? Need to pass the itens id in the path to have access to product node, how can I do this ?
const itens = db.ref();
const eanRef = itens.child('cart').child('itens/{id}').child('product');
To replace the value of an integer variable id to a string itens/{id} you can do the following:
var id = 15;
const itens = db.ref();
const eanRef = itens.child('cart').child('itens/'+id.toString()).child('product');
Use javascript template literals.
const id = 'id-whatever'
const itens = db.ref();
const eanRef = itens.child('cart').child(`itens/${id}`).child('product');

Categories

Resources