Intro: I am using fetch method to get data from API. inside forloop i am not using the template string because somebody told me. it is not a good way to write HTML code inside template sting. So that's why i am using javascript DOM Element to render out the data from API. But i am new in JavaScript i want to know how can i write less code with DOM Element. the code below is too much and complicated. I have dropdown menu inside pending-sale div which contain a form attributes. Which I haven't written yet, if i write that dropdown menu code my code will be even more complicated as I write the code..
Needs: i just want to know how can i write my code less and understandable? Can anyone tell me if the code I am writing is correct? If this is not true, please guide me a little...
I would be grateful for any help.
main.js
const orderCard = document.querySelector('#pending-sales');
function pendingSaleBuild() {
orderCard.innerHTML = ''
fetch('/pending-sale-api/')
.then((res) => res.json())
.then((data) => {
data.map(item => {
// card title
const colLg = document.createElement('div')
colLg.classList.add('col-lg-12')
const hPanel = document.createElement('div')
hPanel.classList.add('hpanel')
hPanel.classList.add('hyellow')
const pBody = document.createElement('div')
pBody.classList.add('panel-body')
hPanel.appendChild(pBody)
colLg.appendChild(hPanel)
orderCard.appendChild(colLg)
const h5 = document.createElement('h5');
h5.classList.add('text-capitalize')
// card tilte link
const a = document.createElement('a');
h5.appendChild(a)
linkText = document.createTextNode(item.customers);
a.appendChild(linkText);
a.href = "#";
pBody.appendChild(h5);
// hr Element
const hr = document.createElement('hr');
pBody.appendChild(hr)
// row div
const rowDiv = document.createElement('div');
rowDiv.classList.add('row');
// project - label div
const colDiv = document.createElement('div');
colDiv.classList.add('col-sm-4');
rowDiv.appendChild(colDiv);
// project lable div
const proLable = document.createElement('div');
proLable.classList.add('project-label');
proLable.innerText = 'Saler Name';
colDiv.appendChild(proLable);
// small text Element
const smallEle1 = document.createElement('small')
smallEle1.innerText = item.saler
colDiv.appendChild(smallEle1);
const colDiv2 = document.createElement('div');
colDiv2.classList.add('col-sm-4');
rowDiv.appendChild(colDiv2);
// project lable div
const proLable2 = document.createElement('div');
proLable2.classList.add('project-label');
proLable2.innerText = 'Timestamp';
colDiv2.appendChild(proLable2);
// small text Element
const smallEle2 = document.createElement('small')
smallEle2.innerText = 'item.created_on'
colDiv2.appendChild(smallEle2);
const colDiv3 = document.createElement('div');
colDiv3.classList.add('col-sm-4');
rowDiv.appendChild(colDiv3);
// project lable div
const proLable3 = document.createElement('div');
proLable3.classList.add('project-label');
proLable3.innerText = 'Total Price';
colDiv3.appendChild(proLable3);
// small text Element
const smallEle3 = document.createElement('small')
smallEle3.innerText = '$ 124547'
colDiv3.appendChild(smallEle3);
pBody.appendChild(rowDiv);
})
});
};
Related
So I have this html code i'm trying to replicate using dom manipulation
<h1 id="intro-text">
HAMADILYTICAL<span id="word">Grill</span>
</h1>
I have some styling for that specific span so that it doesn't render in the same line.
This is what I tried but it's obviously not going to work because I'm appending the child after that node not inside of it.
// main content
const mainContent = document.createElement('div');
const introText = document.createElement('h1');
const span = document.createElement('span');
mainContent.className = 'main-content';
introText.id = 'intro-text';
span.id = 'word';
introText.textContent = `HAMADILYTICAL Grill`;
content.appendChild(mainContent);
mainContent.appendChild(introText);
introText.appendChild(span);
using innerHTML fixed it
const mainContent = document.createElement('div');
const introText = document.createElement('h1');
mainContent.className = 'main-content';
introText.id = 'intro-text';
introText.innerHTML = `<h1 id="intro-text">
HAMADILYTICAL <span id="word">Grill</span></h1>`;
content.appendChild(mainContent);
mainContent.appendChild(introText);
FYI: It is desirable that solutions be strictly vanilla Javascript.
How can I append an HTMLElement object to the middle of an element?
Here's a sample with a bit of what I mean.
const paragraph = document.createElement('p')
paragraph.innerHTML = 'Here is some text.<br><br>There is some text.'
document.body.appendChild(paragraph)
const wrappper = document.createElement('div')
const button = document.createElement('button')
button.onmouseup = () =>
{
// Do something
}
wrapper.appendChild(button)
Now imagine for a moment that I want to put the wrapper element inside of the paragraph element. But, not at the beginning or the end of it, but rather somewhere in the middle such as between the <br> tags. (But not necessarily after a tag) This can be done rather easily by taking the outerHTML of wrapper and inserting it into the paragraph's innerHTML via substrings, but this presents a problem. The resulting elements now in the flow of the html page are not the same as wrapper or button, which is evident when logging them, or when there is no onmouseup event being triggered.
So, ultimately, how do I put the exact HTMLElements referenced by the defined variables into the flow of the document in the middle of the contents of another element?
Find the <br> element and use insertAdjacentElement to insert after it.
const paragraph = document.createElement('p')
paragraph.innerHTML = 'Here is some text.<br><br>There is some text.'
document.body.appendChild(paragraph)
const wrappper = document.createElement('div')
const button = document.createElement('button')
button.innerText = 'Click';
const br = paragraph.querySelector("br");
br.insertAdjacentElement('afterend', button);
Maybe have a temporary <span> with a known id and then replace it with the element you wish to replaceWith would do...
const paragraph = document.createElement('p')
paragraph.innerHTML = 'Here is some text.<br><span id="destination"></span><br>There is some text.'
document.body.appendChild(paragraph)
const wrapper = document.createElement('div')
const button = document.createElement('button')
button.innerText = "here"
button.onmouseup = () =>
{
// Do something
}
wrapper.appendChild(button)
let destination = document.querySelector("#destination")
destination.replaceWith(wrapper)
I am working on an app which fetch the data from API and create a list of the books based on the data received from API. it's an API which gives book titles and information. I generated dynamic li elements and generated a button inside the li. each button has a hidden input element which keep book titles in it. the problem is I'm trying to define a onclick event listener for buttons, since buttons are generated dynamically they don't have id. I want to create an event listener for buttons so that once one specific button is clicked the value of hidden input element that is defined inside the button is passed. I couldn't figure out a way to do that. how to make it to understand which specific button has been clicked so it return the input value that is attached to it.
any help would be really appreciated.
here is a portion of my code.
async function overViewMaker(){
const response = await fetch(api_url_overview.concat(api_key));
let data = await response.json();
data = data.results.lists;
data.forEach(book => {
let mybook = book.books;
mybook.forEach(eachbook => {
var book_div = document.getElementById('book_list');
var liTag = document.createElement("li");
var aTag = document.createElement("buttom");
var inpuHidden = document.createElement("input");
inpuHidden.setAttribute("type", "hidden");
inpuHidden.value = eachbook.title;
aTag.appendChild(inpuHidden);
liTag.appendChild(aTag);
book_div.appendChild(liTag);
});
});
}
Each button is already an element object and so you can use addEventListener directly on the element.
async function overViewMaker() {
const response = await fetch(api_url_overview.concat(api_key));
let data = await response.json();
data = data.results.lists;
// moved book_div out of for loop so it doesn't need to be re-queried for every book
var book_div = document.getElementById("book_list");
data.forEach((book) => {
let mybook = book.books;
mybook.forEach((eachbook) => {
var liTag = document.createElement("li");
var aTag = document.createElement("button");
var inpuHidden = document.createElement("input");
inpuHidden.setAttribute("type", "hidden");
inpuHidden.value = eachbook.title;
aTag.appendChild(inpuHidden);
aTag.addEventListener("click", (ev) => {
// you don't need to get book title from the hidden input element since it is in the scope
// inputHidden.value is also accessible from inside of here
const title = eachBook.title;
console.log(title);
});
liTag.appendChild(aTag);
book_div.appendChild(liTag);
});
});
In the function below, I create cards that have a toggle button and remove button. However, when I try to access the buttons with a queryselector, I get null. Anyone know how to access elements that were created in a different file? I can provide the full files if needed.
function updateDisplay() {
for (i = 0; i < myLibrary.length; i++){
let div = document.createElement('div');
let title = document.createElement('h5');
let author = document.createElement('h5');
let pages = document.createElement('h5');
let isRead = document.createElement('h5');
let removeButton = document.createElement('button');
let toggleButton = document.createElement('button');
div.classList.add('card');
title.classList.add('title');
author.classList.add('author');
pages.classList.add('pages');
isRead.classList.add('isRead');
removeButton.classList.add('removeButton');
toggleButton.classList.add('toggleButton');
title.textContent = myLibrary[i].title;
author.textContent = myLibrary[i].author;
pages.textContent = `${myLibrary[i].pages} pages`;
isRead.textContent = myLibrary[i].isRead ? 'Read' : 'Unread';
removeButton.textContent = 'Remove';
toggleButton.textContent = 'Toggle Read Status';
Your problem is obvious you're creating the elements but not appending the into the body.
you'll have to append each element you create like the following example:
var element= document.createElement("div"); // Create a <div> element
element.innerHTML = "some content"; // Insert text
document.body.appendChild(element); // Append <div> to <body>
note that you can do document.body.append(div,title,author,pages,isRead,removeButton,toggleButton);
to append them all in one line
I'm trying to make a news page in Javascript where every article is on a card. Every card has a headline, an image and the author's name. The headlines show up fine, but the images are broken and the author names don't show up at all. My code looks like this:
function cardCreator(e) {
const cards = document.querySelector('.cards-container');
function cardCreator(e) {
const card = document.createElement('div');
card.classList.add('card');
const headline = document.createElement('div');
headline.classList.add('headline');
headline.textContent = e.headline;
card.appendChild(headline);
const author = document.createElement('div');
author.classList.add('e.author');
card.appendChild(author);
const container = document.createElement('div');
container.classList.add('img');
author.appendChild(container);
const img = document.createElement('img');
img.src = e
container.appendChild(img);
const span = document.createElement('span');
author.appendChild(span);
span.text = `By ${author}`
cards.appendChild(card);
return card;
}
I thought it was the img src, but if I change out the e the whole page breaks so I'm at a loss. Any help would be appreciated.