Trying to make divs inside divs with a loop - javascript

I'm trying to make div's with a loop and my data and in this divs i would like to make at the same time some other div's i tryed something but i think this is the wrong way to do it it would be great if someone could show me a example to make something like this so that in the end it should look like this:
<div class="col-3 vehicleholder" id="THE ID">
<div class="vehicle-icon">
<i class="fas fa-car"></i> <-- The Icon
</div>
<div class="vehicle-information">
<div class="car-name">THE VEH MODEL</div>
<div class="numberplates">THE PLATENUMBERS</div>
</div>
</div>
let app = JSON.parse(parkedvehicle);
const vehiclelist = document.querySelector('div.row vehicles')
for (i = 0; i < app.length; i++) {
let vehicleholder = document.createElement('div');
vehicleholder.classList.add('col-3', 'vehicleholder');
let id = app[i].id;
vehicleholder.setAttribute('id', id);
const vehicleinfo = document.querySelector('div.col-3 vehicleholder')
let vehicleicondiv = document.createElement('div');
vehicleicondiv.classList.add('vehicle-icon');
const vehicleinfoicon = document.querySelector('div.vehicle-icon');
let vehicleicon = document.createElement('i');
vehicleicon.classList.add('fas', 'fa-car');
//
const vehicleinfotext = document.querySelector('div.col-3 vehicleholder')
let vehicleicondiv2 = document.createElement('div');
vehicleicondiv2.classList.add('vehicle-information');
const vehicletext = document.querySelector('div.vehicle-information')
let vehicleicondiv3 = document.createElement('div');
vehicleicondiv3.classList.add('car-name');
vehicleicondiv3.innerHTML = app[i].vehmodel;
const vehicletext2 = document.querySelector('div.vehicle-icon');
let text = document.createElement('div');
text.classList.add('numberplates');
text.innerHTML = app[i].numberplates;
vehiclelist.appendChild(vehicleholder);
vehicleinfo.appendChild(vehicleicondiv);
vehicleinfoicon.appendChild(vehicleicon);
vehicleinfotext.appendChild(vehicleicondiv2);
vehicletext.appendChild(vehicleicondiv3);
vehicletext2.appendChild(text);

So the easiest way to do so its to create a wrapper.
<div id="wrapper"></div>
then to use for loop and insert the HTML that way:
let wrapper = document.getElementById('wrapper')
let app = JSON.parse(parkedvehicle);
for (let car of app){
wrapper.innerHTML += `
<div class="col-3 vehicleholder" id="${car.id}">
<div class="vehicle-icon">
<i class="fas fa-car"></i>
</div>
<div class="vehicle-information">
<div class="car-name">${car.vehmodel}</div>
<div class="numberplates">${car.numberplates}</div>
</div>
</div>
`
}
so what i did, inside the wrapper innerHTML i used `` (template literals) so i can write HTML, any javascript i want to implement i wrapped in ${} and all of this inside the for loop. notice that i wrote: wrapper.innerHTML += so it can add the code block again and again.
this is a codepen for example:
https://codepen.io/Elnatan/pen/eYZYZey
hope it helped you.

Simplest way is to use template literals
For example (this goes in the for loop)
const HtmlCode =
`<div class="col-3 vehicleholder" id="${app[i].id}">
<div class="vehicle-icon">
<i class="fas fa-car"></i>
</div>
<div class="vehicle-information">
<div class="car-name">${app[i].VEH}</div>
<div class="numberplates">${app[i].plateNumbers}</div>
</div>
</div>`;
vehiclelist.innerHTML += HtmlCode;

Related

How to hide DIV's parent in JS with a specific content

I'm trying to hide a DIV's parent when a certain DIV contains a specific text.
An example. This DIV I want to stay:
<div class="report-per-day">
<div class="report-day">26 May 2022</div>
<div class="status-report-rows">
<p class="report__headline">This is our report</p>
</div>
</div>
</div>
But I want to hide this whole DIV, because there's a DIV .mt-2, which contains "No new incident."
<div class="report-per-day">
<div class="report-day">25 May 2022</div>
<div class="mt-2" style="display: none;">
<small class="text-muted">No new incident.</small>
</div>
</div>
</div>
I have this Java Script, but it only hides the .mt-2. I'd also like to hide its 2 parents, .report-per-day and .report-day
Do you guys happen to have any suggestions? Thanks a lot!
const divs = document.getElementsByClassName('mt-2');
for (let x = 0; x < divs.length; x++) {
const div = divs[x];
const content = div.textContent.trim();
if (content == 'No incidents reported.') {
div.style.display = 'none';
}
}
Loop the parent div you want to hide instead of mt-2 and check the content of mt-2 inside the loop. Try:
const divs = document.getElementsByClassName('report-per-day'); // report-per-day instead of mt-2
for (let x = 0; x < divs.length; x++) {
const div = divs[x].querySelector('.mt-2'); // add a selector for .mt-2
const content = div.textContent.trim();
if (content == 'No incidents reported.') {
div.style.display = 'none';
}
}
You can use parentElement
const divs = document.getElementsByClassName('mt-2');
for (let x = 0; x < divs.length; x++) {
const div = divs[x];
const content = div.textContent.trim();
if (content === 'No new incident.') {
div.parentElement.style.display = 'none';
}
}
<div class="report-per-day">
<div class="report-day">26 May 2022</div>
<div class="status-report-rows">
<p class="report__headline">This is our report</p>
</div>
</div>
<div class="report-per-day">
<div class="report-day">25 May 2022</div>
<div class="mt-2">
<small class="text-muted">No new incident.</small>
</div>
</div>

Why does the addEventListener property does not work on a dynamic HTMLcollection object?

I am working on a chrome extension and trying to add an event listener to a getElementsByClassName variable, in which elements are added dynamically using template strings.
I have tried a lot of changes in the code, but the code doesn't work.
The code is supposed to delete the targeted element from the array "recipeList", storing the array in localStorage and then render the updated array "recipeList" using template string to the HTML code again.
DELETE BUTTON Function
let delBtn = document.getElementsByClassName("del-btn");
for(let i = 0; i < delBtn.length; i++) {
delBtn[i].addEventListener("click", function() {
recipeList.splice(i, 1);
localStorage.setItem("recipeList", JSON.stringify(recipeList));
recipeList = JSON.parse(localStorage.getItem("recipeList"));
render(recipeList);
if(!recipeList.length) {
tabBtn.style.width = "100%";
delAllBtn.style.display = "none";
}
});
}
RENDER CODE
function render(list) {
let recipeURL = "";
for(let i = 0; i < list.length; i++) {
recipeURL += `
<div class="mb-2 row">
<div class="col-1 num-btn">
${i+1}
</div>
<div class="col-10">
<div class="recipe-url">
<a target="_blank" href="${list[i]}">
${list[i]}
</a>
</div>
</div>
<div class="col-1 del-btn">
<a href="#">
<i class="bi bi-trash-fill"></i>
</a>
</div>
</div>
`
}
urlList.innerHTML = recipeURL;
console.log(delBtn);
}
When you render, you create new .del-btn which are not included in your first let delBtn = document.getElementsByClassName("del-btn");.
Each time you create new .del-btn, you should also add a new listener.
function render(list) {
let recipeURL = "";
for(let i = 0; i < list.length; i++) {
recipeURL += `
<div class="mb-2 row">
<div class="col-1 num-btn">
${i+1}
</div>
<div class="col-10">
<div class="recipe-url">
<a target="_blank" href="${list[i]}">
${list[i]}
</a>
</div>
</div>
<div class="col-1 del-btn">
<a href="#">
<i class="bi bi-trash-fill"></i>
</a>
</div>
</div>
`
}
urlList.innerHTML = recipeURL;
console.log(delBtn);
Array.from(urlList.querySelectorAll('.del-btn')).forEach((btn, i) => {
btn.addEventListener('click', () => console.log('.del-btn index: ' + i))
})
}
}

How to change the id of an element in html using javascript?

It is my first time using JavaScript. I am trying to make a button where every time visitors click, it'll show another extra line of text. I often get an error on my JavaScript, and I'm not sure how to fix it. Thank you so much!
HTML;
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<div class="text">
<div class="one hide">
One
</div>
<div class="two hide">
Two
</div>
<div class="three hide">
Three
</div>
</div>
</div>
</body>
<script src="script.js"></script>
</html>
JS;
const text = document.querySelector('.text');
const hide = document.querySelector('.hide');
const one = document.querySelector('.one');
const two = document.querySelector('.two');
var hr1 = document.getElementById('hr1');
var hr2 = document.getELementById('hr2');
var hr3 = document.getElementById('hr3');
hr1.addEventListener('click', () => {
one.classList.remove('hide');
hr1.id = "hr2";
})
// I often get an error on hr2.addEventListener
hr2.addEventListener('click', () => {
two.classList.remove('hide');
hr2.id = "hr3";
})
Your code throws error because you are trying to set hr2 and hr3 when they are not exist.
You need to set hr2 and hr3 variables after setting id's of them like below:
hr1.id = "hr2";
hr2= document.getElementById('hr2');
const text = document.querySelector('.text');
const hide = document.querySelector('.hide');
const one = document.querySelector('.one');
const two = document.querySelector('.two');
var hr1 = document.getElementById('hr1');
var hr2 = null;
var hr3 = null;
hr1.addEventListener('click', () => {
//one.classList.remove('hide');
hr1.id = "hr2";
hr2= document.getElementById('hr2');
console.log(hr2);
hr2.addEventListener('click', () => {
two.classList.remove('hide');
hr2.id = "hr3";
hr3 = document.getElementById('hr3');
console.log(hr3);
})
})
// I often get an error on hr2.addEventListener
<div class="container">
<div class="text">
<div class="one hide">
One
</div>
<div class="two hide">
Two
</div>
<div class="three hide">
Three
</div>
</div>
clickme
</div>

Get Element and append multiple times Javascript

I need to get an element and append it multiple times inside its parent.
HTML
<main>
<div class="wrapper">
<img src="https://placeimg.com/300/300/arch?t=1493746896324/" />
<div class="cover"></div>
</div>
</main>
JS
const main = document.querySelector("main");
const wrapper = document.querySelector(".wrapper");
for (let index = 0; index < 10; index++) {
main.innerHTML += wrapper;
}
RESULT
[object HTMLDivElement] is inserted instead.
Cloning a Node
ParentNode.append()
Node.cloneNode()
const main = document.querySelector("main");
const wrapper = document.querySelector(".wrapper");
for (let index = 0; index < 10; index++) {
main.append(wrapper.cloneNode(true));
}
<main>
<div class="wrapper">
<img src="https://placeimg.com/300/300/arch?t=1493746896324/" />
<div class="cover"></div>
</div>
</main>
Concatenate using outerHTML
Otherwise, given innerHTML and manipulating Strings you could do:
Element.innerHTML
Element.outerHTML
const main = document.querySelector("main");
const wrapper = document.querySelector(".wrapper");
for (let index = 0; index < 10; index++) {
main.innerHTML += wrapper.outerHTML;
}
<main>
<div class="wrapper">
<img src="https://placeimg.com/300/300/arch?t=1493746896324/" />
<div class="cover"></div>
</div>
</main>
Pros Cons
Both the above results will end up in the same markup
<main>
<div class="wrapper">...</div>
......
<div class="wrapper">...</div>
</main>
with the only difference that by using cloning with true, every originally assigned listeners or data will be cloned as well;
whilst using concatenation += with .outerHTML() is basically a simple HTML markup concatenation with not much other benefits.

Append div in button on click Javascript

Hi how to append div inside button on click this is my JavaScript:
function addLoader() {
var div = document.createElement('div');
div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
var test01 = document.createElement('button');
test01.appendChild(div);
console.log(test01);
}
I want to add innerHTML inside button tags on click
<button onclick="addLoader(this);">testt </button>
It must be like this when function is finish :
<button>testt <div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div> </button>
HTML
// Added id attribute
<button onclick="addLoader();" id = "test01">testt </button>
JS
function addLoader() {
var _div = document.createElement('div');
_div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
//append _div to button
document.getElementById("test01").appendChild(_div);
}
Working jsfiddle
EDIT
This will append element to any button call addLoader on click
function addLoader(elem) {
var _div = document.createElement('div');
_div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
elem.appendChild(_div);
}
Updated jsfiddle
var btn = document.getElementById("addLoader");
if (btn) {
btn.addEventListener('click', addLoader, false);
}
function addLoader() {
var div = document.createElement('div');
div.innerHTML = '<div class="loader"> <div class="loader-ring"> <div class="loader-ring-light"></div> </div> </div>';
this.appendChild(div);
}
<button id="addLoader">Test</button>
You just need one more line of code. The variable test01 is created in memory but not added to the DOM. You must append this new element to the DOM (ie. document.appendChild(test01))

Categories