I want to add divs by using JavaScript in the parentDiv. I have already created some divs in my index.html file. I want that the div I will create will be added before other divs I created in html in the same parentDiv. I don't want to remove other divs. I tried using appendChild but that adds in the end. Hope it makes sense.
function displayBox(data) {
let html = "";
data.forEach((box) => {
const box = document.createElement("div");
box.classList.add("box");
html = `
<a
target="_blank"
href="${box.link}"
class="image fit"
><img
src="${box.img}"
alt="${box.name}"
/></a>
<div class="inner">
<h3>${box.name} (${box.country})</h3>
<a
target="_blank"
href="${box.link}"
class="button open-link fit"
>Visit</a
>
</div>
`;
box.innerHTML = html;
thumbnails.appendChild(box);
});
}
thumbnails is my parentDiv where I want to add divs named box
If you want to add elements to the front you can use prepend.
var data = [1,2,3];
var out = document.querySelector("#out");
data.forEach(function (x) {
var div = document.createElement("div");
div.textContent = x;
out.prepend(div);
});
<div id="out">
<div>Orginal</div>
</div>
If you want to not be in revser order, you can either loop in reverse or change the code to use before() with the first element in the parent.
var data = [1,2,3];
var out = document.querySelector("#out");
const first = out.children[0];
data.forEach(function (x) {
var div = document.createElement("div");
div.textContent = x;
first.before(div);
});
<div id="out">
<div>Orginal</div>
</div>
It solved the problem in this way. Thanks epascarello
function displayBox(data) {
data = data.reverse();
let html = "";
data.forEach((box) => {
const box = document.createElement("div");
box.classList.add("box");
html = `
<a
target="_blank"
href="${box.link}"
class="image fit"
><img
src="${box.img}"
alt="${box.name}"
/></a>
<div class="inner">
<h3>${box.name} (${box.country})</h3>
<a
target="_blank"
href="${box.link}"
class="button open-link fit"
>Visit</a
>
</div>
`;
box.innerHTML = html;
thumbnails.prepend(box);
});
}