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

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.

Related

forEach loop keeps appending to first child element only

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

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

check for duplicate before appendChild

const pickNewUl = document.getElementById("ullist1");
var createLi = document.createElement("li");
createLi.id = listItems[i].id;
createLi.classList.add(pickNewUlsl);
createLi.innerHTML = listItems[i].textContent;
createLi.innerHTML += "<a onclick='remove(this)' class='removebtn'>X</a>";
pickNewUl.appendChild(createLi);
What I need to check in above code is: I want to check if there are any same id LI exists or not, if not then only it should append, otherwise it will not append.
pickNewUl is a UL list
You can find for any element inside element with .querySelectorAll as below.
if (pickNewUl.querySelectorAll('#' + listItems[i].id).length === 0) {
// Add element
}
Reference : https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
Your complete code should be like below.
const pickNewUl = document.getElementById("ullist1");
if (pickNewUl.querySelectorAll('#' + listItems[i].id).length === 0) {
var createLi = document.createElement("li");
createLi.id = listItems[i].id;
createLi.classList.add(pickNewUlsl);
createLi.innerHTML = listItems[i].textContent;
createLi.innerHTML += "<a onclick='remove(this)' class='removebtn'>X</a>";
pickNewUl.appendChild(createLi);
}
You can just wrap you code inside an if:
// the same as before but using pickNewUl instead of document
if (!pickNewUl.getElementById(listItems[i].id)) {
const createLi = document.createElement("li");
...
pickNewUl.appendChild(createLi);
}
Btw, I suggest to use a different approach excluding duplicated id:
// The string into querySelector method is a template string.
if (!pickNewUl.querySelector(`[data-item-id="${listItems[i].id}"]`)) {
const createLi = document.createElement("li");
createLi.dataset.itemId=listItems[i].id;
...
pickNewUl.appendChild(createLi);
}

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(''));
}

Insert data from an Array into different HTML Divs

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;

Categories

Resources