Adding a div with CSS to DOM - javascript

For a project, I am building an app that gets user input, stores it in an array, and displays the input in the DOM. I did the first two parts but I am having trouble displaying it. More specifically, I can't get the CSS to show up.
I have tried .createElement() which creates a new list-item but it does not include CSS. I am starting to think I am completely going about this incorrectly. If you need more information or code let me know.
\\HTML
<div id="boxhold">
<ul>
<li>
<div class="twogrid">
<h1>Fruit Juice</h1>
<p>50</p>
</div>
</li>
</ul>
</div>
\\CSS
#boxhold {
margin: 0 auto;
ul {
list-style-type: none;
padding: 0;
li {
margin: 0 auto;
width: 408px;
height: 75px;
border: 3px solid $prime-color;
h1 {
font-family: $header-font;
font-weight: $header-weight;
font-size: 1em;
}
p {
font-family: $header-font;
font-weight: $header-weight;
}
}
}
}
\\JS
//Get Data
//Empty array for storing
var added = [];
//Get Data
var userInput = function() {
return {
name: document.getElementById('name').value,
amount: document.getElementById('amount').value
}
};
// Store Data
var newSugar = function(){
return added.push(userInput());
}
// New HTML
function newBox() {
var newLi = document.createElement('li');
var newName = document.getElementById('name').value;
var n = document.createTextNode(newName);
newLi.appendChild(n);
var newAmount = document.getElementById('amount').value;
var a = document.createTextNode(newAmount);
newLi.appendChild(a);
var boxhold = document.getElementById('boxhold').getElementsByTagName('ul')[0];
document.body.appendChild(newLi);
};
//Adding stuff
var displayData = (function() {
var addInput = function() {
var data = userInput();
var item = newSugar();
var box = newBox();
//var box = newItem();
};
var addFood = document.getElementById('addFood');
addFood.addEventListener('click', addInput);
document.addEventListener('keypress', function(event) {
if (event.keyCode === 13 || event.which === 13) {
addInput();
}
});
})(userInput, newSugar, newBox);

Welcome to Stack Overflow #nzart 👋
It looks like you're appending the newly created list item to the document's body, which means it will be added as the last element of the page. Your CSS indicates that the styles only apply to list items inside of an unordered list, so this would explain the lack of styles.
The simple fix should be to replace document.body.appendChild(newLi); with boxhold.appendChild(newLi);. I hope this helps!

Related

html input create li element how to set an id for the element

I'm new with HTML & JS and I face the following problem:
I have an input in html that creates a new li Element (in combination with JS); is it possible to give every newly-created li element its own id? For example to delete an specific element?
For Example:
<li id="one"> .. </li>
<li id="two"> .. </li>
So far it creates only <li> ... </li>
I think it can be done with a for loop, but I have no idea how to use it in my case.
See my JS code below:
function NewEntry() {
var Inputfield = document.getElementById("Inputfield");
var AddButton = document.getElementById("AddButton");
var ul = document.querySelector("ul");
var li = document.createElement("li");
li.appendChild(document.createTextNode(Input.value));
ul.appendChild(li);
Input.value = "";
I tried to insert a for loop into my code, but after that it doesn't add any elements.
function NewEntry() {
var Inputfield = document.getElementById("Inputfield");
var AddButton = document.getElementById("AddButton");
var ul = document.querySelector("ul");
var li = document.createElement("li");
for (var i = 0; i < li.length; i++)
li[i].id = 'abc-' + i;
li.appendChild(document.createTextNode(Input.value));
ul.appendChild(li);
Input.value = "";
Your for loop needs curly braces to work properly:
function NewEntry() {
var Inputfield = document.getElementById("Inputfield");
var AddButton = document.getElementById("AddButton");
var ul = document.querySelector("ul");
var li = document.createElement("li");
for (var i = 0; i < li.length; i++) {
abcElements[i].id = 'abc-' + i;
li.appendChild(document.createTextNode(Inputfield.value));
ul.appendChild(li);
}
Inputfield.value = "";
}
Otherwise only the immediate line after the for statement will run as part of the loop.
There also appeared to be a typo - you had Input instead of Inputfield? But I notice there are some other variables used here which are not defined, so I assume some extra code was omitted?
You could count the number of elements inside the <ul> and use that as id for the <li>:
var AddButton = document.getElementById("AddButton");
AddButton.addEventListener("click", NewEntry);
function NewEntry() {
var Inputfield = document.getElementById("Inputfield");
var ul = document.querySelector("ul");
var li = document.createElement("li");
li.id = ul.childElementCount;
li.appendChild(document.createTextNode(Inputfield.value));
ul.appendChild(li);
Inputfield.value = "";
console.log(li);
}
<input type="text" id="Inputfield" />
<button id="AddButton">Add</button>
<ul></ul>
One simple means by which this could be accomplished is as follows, with explanatory comments in the JavaScript:
// a generator function, to generate a constantly increasing counter:
const generator = function*() {
// the initial value of the counter:
let i = 0;
// this loop causes the generator to return a number infinitely
// though while the loop is infinite it yields one value and then
// pauses until the next call; this is one instance where an
// infinite loop is deliberate and not a problem:
while (true) {
// increments the value of i, and then returns it to the
// calling context:
yield ++i;
}
},
// assigning a reference to the generator:
counter = generator(),
// a simple Arrow function that takes two arguments:
// tag: String, the element-type to create, and
// props: an Object of element-properties and values to
// assign to the created element:
create = (tag, props) => Object.assign(document.createElement(tag), props),
// a reference to the various elements to which event-listeners are attached:
list = document.querySelector('#list'),
form = document.querySelector('form'),
input = document.querySelector('input'),
button = document.querySelector('#add'),
// the addNew function, written as an Arrow function:
addNew = () => {
// caching the source of the text:
const inputField = document.querySelector('input');
// here we take the value, trim it to remove leading and trailing
// white-space, and then retrieve its length; if there is a zero
// length (so either nothing was entered, or only whitespace) then
// we return here:
if (inputField.value.trim().length === 0) {
return false;
}
// otherwise we cache a reference to the element to which the
// created <li> element will be appended:
const ul = document.querySelector('#list'),
// we call the create() function, here creating an <li>
// element, and passing in an object of properties and
// values:
li = create('li', {
// we set the 'id' - using a template literal string - to
// the string of 'abc-' plus next-value of the counter:
id: `abc-${counter.next().value}`,
// and set the text-content of the element to the
// trimmed value of the <input>:
textContent: inputField.value.trim()
}),
// here we create a <button>,
deleteButton = create('button', {
// with its className set to 'delete':
className: 'delete',
// its text-content set to 'delete task':
textContent: 'delete task',
// and its type set to 'button' in order to
// prevent the <button> submitting the <form>:
type: 'button'
});
// we append the created <button> to the created <li>:
li.append(deleteButton);
// we append the <li> to the <ul>:
ul.append(li);
// and reset the value of the <input> to an empty string:
inputField.value = '';
};
// here we prevent form submission:
form.addEventListener('submit', (e) => e.preventDefault());
// here we bind an anonymous function as the event-handler of the
// 'keyup' event on the <input> element:
input.addEventListener('keyup', (evt) => {
// if the, or an, 'Enter' key is pressed (note that evt.keyCode is
// almost entirely deprecated now, but is here for backwards
// compatibility, it can and possibly should be removed):
if (evt.key === 'Enter' || evt.keyCode === 13) {
// here we call the addNew() function:
addNew();
}
});
// we bind the addNew() function - note the deliberate lack of
// parentheses - as the event-handler for the 'click' event:
button.addEventListener('click', addNew);
// because we're adding the delete <button> elements we delegate the
// event-handling to the closest ancestor element present in the DOM
// on page-load, here that's the #list element. Here we bind the
// anonymous function as the event-handler for the 'click' event
// which bubbles to the <ul>:
list.addEventListener('click', (evt) => {
// if the element on which the click event fired has an ancestor
// .delete element (therefore it was fired on, or in, the .delete
// <button>):
if (evt.target.closest('.delete')) {
// we navigate from the event-target to the closest <li>
// ancestor element and use Element.remove() to remove that
// element from the document:
evt.target.closest('li').remove();
}
})
*,
::before,
::after {
box-sizing: border-box;
font-family: system-ui;
font-size: 16px;
margin: 0;
padding: 0;
}
main {
inline-size: clamp(15em, 80vw, 1000px);
margin-inline: auto;
}
h2 {
font-size: 1.4em;
text-align: center;
}
fieldset {
display: grid;
padding: 0.5em;
}
legend {
border-inline: 1px solid currentColor;
border-radius: 0.25em;
margin-inline: 1em;
padding-inline: 0.5em;
}
label {
display: flex;
gap: 1em;
justify-content: space-between;
margin-block: 0.5em;
}
label input[type=text] {
flex-grow: 1;
}
#list {
border: 1px solid currentColor;
display: grid;
gap: 0.5em;
list-style-type: none;
margin-block: 1em;
margin-inline: auto;
padding: 0.5em;
}
#list:empty::before {
color: hsl(0deg 30% 30% / 0.8);
content: "A beautiful, quiet day of reflection...";
font-style: italic;
}
#list li {
background-color: lavender;
display: grid;
padding: 0.25em;
}
#list li:nth-child(odd) {
background-color: lightcyan;
}
li[id]::before {
content: "#" attr(id) ": ";
}
.delete {
justify-self: end;
}
<main>
<section>
<h2>To do list</h2>
<form action="#" method="post">
<fieldset>
<legend>New task</legend>
<label>
<span class="labelText">What do you want to do today?</span>
<input type="text">
</label>
<button id="add" type="button">Add task to list</button>
</fieldset>
</form>
<ul id="list"></ul>
</section>
</main>
JS Fiddle demo.
It's worth noting that there is one potential issue using a generator function to generate a counter for an id property; the counter will only ever increase, so if you have three elements abc-1, abc-2, abc-3 and then delete those, and create another three elements those elements will continue from abc-4. So the id will be independent of the number of created elements. This may be a benefit in that a duplicate value can't be created, so there's little chance of a duplicate id being created by a generator.
References:
Arrow functions.
document.createElement().
document.querySelector().
Element.append().
Element.remove().
EventTarget.addEventListener().
Generator functions (function*(){...}).
Object.assign().
String.prototype.trim().
Template literals.
while loop.

Re: How to target child nodes in HTML collection

I am new to programming and this is my first question. The problem I am having is I am trying to use DOM manipulation on all the child nodes of an html collection. I am expecting the nodes to change background color when they are hovered. Here is what I have tried so far:
let x = 0;
do{
const square = document.createElement("div");
square.className = "squares";
square.setAttribute("id","block");
document.getElementById("container").appendChild(square);
x++;
}
while(x < 16);
var container = document.getElementById("container");
var cells = container.childNodes;
cells.forEach(function(){
cells.onmouseover = function(){
cells.style.backgroundColor = "black";
}
});
console.log(`${cells.length}`);
This doesn't work even though console.log shows 16 child nodes being targeted.
var container = document.getElementById("container");
var cells = container.children[0];
cells.onmouseover = function(){
cells.style.backgroundColor = "black";
}
I have tried this and can use index but of course only that cell will change bg color. I want any cell that is hovered to change also.
I am at a loss for what I am doing wrong here. If anyone can point me in the right direction I would greatly appreciate it.
Welcome to Stack Overflow.
There is an issue in your forEach cycle. Consider the following:
cells.forEach(cell => {
cell.onmouseover = () => {
cell.style.backgroundColor = "black"
}
})
Note that you need to refer to cycle variable instead of the cells array.
Instead of attaching listeners to all the squares you can use event delegation and just have one listener on the container that captures the events from its children as they "bubble up" the DOM.
// Cache the container element, and add a listener to it
const container = document.querySelector('.container');
container.addEventListener('mouseover', handleMouse);
// Create some squares HTML by pushing template
// strings into an array
const html = [];
for (let i = 1; i < 10; i++) {
html.push(`<div class="square">${i}</div>`);
}
// Add that HTML to the container making sure
// we join the array of strings into one string
container.innerHTML = html.join('');
// When a event is fired check that it was
// was from an element with a square class
// and then add an active class to it
function handleMouse(e) {
if (e.target.matches('.square')) {
e.target.classList.add('active');
}
}
.container { display: grid; grid-template-columns: repeat(3, 50px); grid-gap: 0.2em; }
.square { font-size: 1.2em; padding: 0.7em 0.2em; background-color: #565656; color: white; text-align: center; }
.square.active { background-color: thistle; color: black; cursor: pointer; }
<div class="container"></div>
Additional documentation
Template/string literals

Detecting HTML changes when adding elements with JavaScript

I'm am having a issue where I have a click event.
This is the code:
for (const button of itemClick) button.addEventListener("click", function() {
clickCount++;
if (clickCount == 1) {
value1 = button.getAttribute("value");
}
if (clickCount >= 2) {
value2 = button.getAttribute("value");
clickCount = 0;
onItemClick();
}
});
itemClick refers to a document classname variable called item
So if I click twice on that item it should add a second item which works but clicking on that item created by JavaScript doesn't want to work so I have to somehow let JavaScript know the HTML has changes so when I click on it it also has effect but I don't know how to do that and can't find any information for it.
I am adding the element in HTML like this:
let itemDiv = document.createElement("div");
let imageDiv = document.createElement("div");
let imgEl = document.createElement("img");
let itHeading = document.createElement("h6");
let itemslistcontent = document.getElementById("items");
itemslistcontent.appendChild(itemDiv);
itemDiv.appendChild(imageDiv);
imageDiv.appendChild(imgEl);
itemDiv.appendChild(itHeading);
itemDiv.classList.add("item");
itemDiv.setAttribute("value", prop);
itHeading.innerHTML = prop;
This is the full function:
function onItemClick() {
for (var prop in itemNames) {
if (itemNames[prop].includes(value1) && itemNames[prop].includes(value2)) {
value1 = "";
value2 = "";
let itemDiv = document.createElement("div");
let imageDiv = document.createElement("div");
let imgEl = document.createElement("img");
let itHeading = document.createElement("h6");
let itemslistcontent = document.getElementById("items");
itemslistcontent.appendChild(itemDiv);
itemDiv.appendChild(imageDiv);
imageDiv.appendChild(imgEl);
itemDiv.appendChild(itHeading);
itemDiv.classList.add("item");
itemDiv.setAttribute("value", prop);
itHeading.innerHTML = prop;
console.log(itemslistcontent);
} else {
value1 = "";
value2 = "";
}
}
}
When you add new elements to the DOM programmatically, those elements are called dynamic.
Since your code is already run when the dynamic elements are added to the DOM, the event listeners are only registered to the elements which were already present at the time of code execution.
Thus, you need to add the event listener again to the dynamic component.
Also, why don't you make use of the dblclick event in JavaScript?
Try the following code, its adding the even listener as and when the dynamic elements are created.
function onItemClick() {
for (var prop in itemNames) {
if (itemNames[prop].includes(value1) && itemNames[prop].includes(value2)) {
value1 = "";
value2 = "";
let itemDiv = document.createElement("div");
let imageDiv = document.createElement("div");
let imgEl = document.createElement("img");
let itHeading = document.createElement("h6");
let itemslistcontent = document.getElementById("items");
itemslistcontent.appendChild(itemDiv);
itemDiv.appendChild(imageDiv);
imageDiv.appendChild(imgEl);
itemDiv.appendChild(itHeading);
itemDiv.classList.add("item");
itemDiv.setAttribute("value", prop);
itHeading.innerHTML = prop;
console.log(itemslistcontent);
// adding the event listener
itemDiv.addEventListener("dblclick", function() {
value2 = button.getAttribute("value");
clickCount = 0;
onItemClick();
});
} else {
value1 = "";
value2 = "";
}
}
}
Event Delegation
The easiest way to track any event (ie "click") on any element of any amount, whether dynamically added or not, is to use Event Delegation.
Register an element that will or is containing all of the buttons we want to monitor/control by way of the "click" event.
// Event Property
document.querySelector('main').onclick = clickHandler;
OR
// EventListener
document.querySelector('main').addEventListener('click', clickHandler);
Whenever this parent element is clicked function clickHandler() will run. This event handler (just a more descriptive name for a function triggered by an event) will delegate the event to the exact button the user clicked by:
using the event.target property to reference the element the user clicked.
narrow it down by the use of if/if else/else conditions, and the .matches() method.
if (event.target.matches('button')) {...
Advantages
We only need to register events to a single parent element. window and document could be used but it's better to use an element further down like <main> or <form> IMO. This parent element can be referenced using event.currentTarget property.
const listener = event.currentTarget;
console.log(listener.tagName); // MAIN
Any descendant element of the event.currentTarget can be selected. If the user clicked an element (ie <button>) then it can be referenced directly with the event.target property. If the desired element isn't event.target, but it is it's proximity, we can reference it indirectly many ways.
<main>
<section class='group'>
<figure class='item'>
<img src='pix.jpg'>
<figcaption>
<input>
<button>X</button>
<label>XXXX</label>
...
const clicked = event.target;
if (clicked.matches('button')) {
let group = clicked.closest('.group');
let item = clicked.closest('.item');
let tag = clicked.nextElementSibling;
let txt = clicked.previousElementSibling;
...
/*
Reference to the <section>, <figure>, <input>,
and <label> and finding the exact element
clicked by user
*/
This delegation also includes any dynamically added elements as well. A common mistake newbies make is expecting elements added to the DOM are clickable, but aren't because they need to be registered to the event (ie .onclick or .addEventListener('click')). This is never a concern using event delegation. Add whatever and whenever to the event.currentTarget; and nothing more.
Demo
const main = document.querySelector('main');
main.onclick = clickHandler;
function clickHandler(event) {
const listener = event.currentTarget;
const clicked = event.target;
let grpIdx = indexNodes('.group');
let itmIdx = indexNodes('.item');
const itemHTMLString = `
<figure class='item'>
<img src="https://placeimg.com/100/100/any">
<figcaption>
<b>Item ${itmIdx+1}</b><button>💀</button>
<output class='count'>0</output>
</figcaption>
</figure>`;
const groupHTMLString = `
<section class='group'>
<fieldset>
<legend>Group ${grpIdx+1} Total Clicks</legend>
<output class='total'>1</output>
</fieldset>
<figure class='item'>
<img src="https://placeimg.com/100/100/any">
<figcaption>
<b>Item ${itmIdx+1}</b><button>💀</button>
<output class='count'>1</output>
</figcaption>
</figure>
</section>`;
let item, group, count, total;
if (clicked.matches('button')) {
item = clicked.closest('.item');
group = clicked.closest('.group');
count = clicked.nextElementSibling;
total = group.querySelector('.total');
let cnt = parseInt(count.textContent, 10);
let ttl = parseInt(total.textContent, 10);
if (ttl < 3) {
total.textContent = ttl + 1;
count.textContent = cnt + 1;
group.insertAdjacentHTML('beforeend', itemHTMLString);
indexNodes('.group');
indexNodes('.item');
} else if (ttl === 3) {
let buttons = group.querySelectorAll('button');
for (let btn of buttons) {
btn.disabled = true;
}
listener.insertAdjacentHTML('beforeend', groupHTMLString);
indexNodes('.group');
indexNodes('.item');
} else {
return false;
}
} else {
return false;
}
}
function indexNodes(selector) {
const nodes = document.querySelectorAll(selector);
nodes.forEach((node, index) => node.dataset.idx = index);
return nodes.length;
}
* {
margin: 0;
padding: 0;
}
main {
margin: 10px auto;
padding: 8px;
}
.group {
display: flex;
flex-flow: row nowrap;
justify-content: flex-start;
margin: 8px auto;
padding: 4px;
}
fieldset {
margin-top: -20px
}
legend {
font-size: large;
font-weight: bold;
}
figcaption {
display: flex;
flex-flow: row nowrap;
justify-content: flex-end;
}
button,
b,
output {
display: block;
font-size: large;
}
b {
text-align: left;
padding: 8px 8px 0 8px;
font-size: small;
}
.count {
padding: 8px 8px 0 8px;
}
.total {
margin: 0 auto;
text-align: center;
}
button {
cursor: pointer;
max-height: 28px;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8'>
</head>
<body>
<main>
<section class='group' data-idx='0'>
<fieldset>
<legend>Group 1 Total Clicks</legend>
<output class='total'>1</output>
</fieldset>
<figure class='item' data-idx='0'>
<img src="https://placeimg.com/100/100/any">
<figcaption>
<b>Item 1</b><button>💀</button>
<output class='count'>1</output>
</figcaption>
</figure>
</section>
</main>
</body>
</html>

Can you save multiple separate lists to localStorage?

I'm working on a project that will take user input and store it into a list in localStorage. I want to be able to have three of these to do lists on the page.
I have put the code into three separate columns, however when I try to submit information in them, it seems to be adding the values in all of the columns to one list. I don't every use JS or Jquery, so I have been trying to learn as I go, and I'm stumped. This is the code that I am looking to run in three separate columns.
How do I make sure that the lists are stored in three separate places and also stored separately in localStorage?
var list = JSON.parse(localStorage.getItem("todolist"));
// Checks for to dos in LS, if none starts with empty array
if (!Array.isArray(list)) {
list = [];
}
function putOnPage() {
$("#todo-list").empty(); // empties out the html
var insideList = JSON.parse(localStorage.getItem("todolist"));
if (!Array.isArray(insideList)) {
insideList = [];
}
// todos to page
for (var i = 0; i < insideList.length; i++) {
var p = $("<p>").text(insideList[i]);
var b = $("<button class='delete'>").text("x").attr("data-index", i);
p.prepend(b);
$("#todo-list").prepend(p);
}
}
// rtodos on page load
putOnPage();
$(document).on("click", "button.delete", function() {
var todolist = JSON.parse(localStorage.getItem("todolist"));
var currentIndex = $(this).attr("data-index");
// deletes items
todolist.splice(currentIndex, 1);
list = todolist;
localStorage.setItem("todolist", JSON.stringify(todolist));
putOnPage();
});
$("input[type='submit']").on("click", function(event) {
event.preventDefault();
// changes input to variable and clears input field
var val = $("input[type='text']").val();
$("input[type='text']").val("");
// adds to do to list and local storage
list.push(val);
localStorage.setItem("todolist", JSON.stringify(list));
putOnPage();
});
You can probably go with making the list an array with three object each one containing a separate column from the page, than update or set using something list[0] for list one, list[1] for list 2 and so on.
Or
You can approach it with using three stores in the localstorage one for each column.
JS Fiddle Example -> https://jsfiddle.net/jassMarok/3gcnyamp/18/
// find elements
var banner = $("#banner-message")
var button = $("button")
var testObject = [{
name: "todo-list1",
items: ["Sell", "Buy", "Donate"]
},
{
name: "todo-list2",
items: ["Go", "Run", "Sleep"]
},
{
name: "todo-list3",
items: ["Work", "Program", "Code"]
}
];
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// handle click and add class
button.on("click", function() {
var lists = $('[id|="list"]');
console.log(lists);
var retrievedObject = JSON.parse(localStorage.getItem('testObject'));
console.log(retrievedObject)
for (i = 0; i < lists.length; i++) {
var $list = lists[i];
var items = retrievedObject[i].items;
for (j = 0; j < items.length; j++) {
console.log(items);
$($list).append('<li>' + items[j] + '</li>');
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
<button>Load Data</button>
<hr/>
<h3>
List 1
</h3>
<ul id="list-1"></ul>
<hr/>
<h3>
List 2
</h3>
<ul id="list-2"></ul>
<hr/>
<h3>
List 3
</h3>
<ul id="list-3"></ul>
</div>

How to map JSON Data from an API to a div

I've been working on an app that fetches data from an API and then neatly puts them into card div's. I've written the code for performing the request and getting all the data in JSON (image below), however I can't find a way to keep my code clean and manage the results.
What i want to do is create a div called card for each JSON object (there are 50 in the picture below) and then inside those divs i append span tags with the information.
Here's my current code
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
results.style.opacity = 1
let result = xhr.responseText
result = JSON.parse(result)
console.log(result)
Create the function and pass the JSON data to that function and then you need to iterate the loop for the key name results. Then access the each element by using the key name of the array's object. Below is the example code (css not included). More about object
<body>
<div id="container">
</div>
</body>
<script>
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
results.style.opacity = 1
let result = xhr.responseText
result = JSON.parse(result)
loadDiv(result);
}
}
function loadDiv(data){
for(var x of data.results){
var div = `<div class="cols">
${x.mal_id}
<img src="${x.url}"/>
</div>
`;
document.getElementById("container").insertAdjacentHTML("beforeend",div);
}
}
You can iterate the object and create divs and spans.
// I expect your results in this variable.
var result = {
results: [{
One: 'div',
Two: 'span'
}]
};
result.results.forEach(data => {
var div = document.createElement('div');
div.id = 'block';
div.className = 'block';
var span = document.createElement('span');
span.className = 'block-2';
div.appendChild(span);
document.getElementsByTagName('body')[0].appendChild(div);
});
.block {
height: 50px;
width: 50px;
border: 1px solid red;
}
.block-2 {
height: 20px;
width: 20px;
border: 1px solid blue;
position: absolute;
}

Categories

Resources