I am trying to add <img> tags dynamically to my DOM using FileSystem to scan through my images folder.
My idea is to create one <img> element for each image I have in the "images" folder.
At the moment I am able or to create the <img> elements or to create an array with the filenames from the folder, but for a mysterious reason, when I join the pieces nothing works.
Someone could help me to figure out what is happening.
const imgContainer = document.getElementById("cover");
const newDiv = document.createElement("div");
newDiv.setAttribute("class", "image-ctn");
imgContainer.appendChild(newDiv);
const addImage = (imgSource) => {
const newImage = document.createElement("img");
newImage.setAttribute("class", "face");
newImage.src = `images/${imgSource}`;
imgContainer.appendChild(newDiv);
newDiv.appendChild(newImage);
};
//
const fs = require("fs");
const imagesPath = "images";
const pattern = ".jpg";
let imageArray = fs.readdirSync(imagesPath).filter((str) => {
return str.includes(pattern);
});
imageArray.map((imageFile) => {
addImage(imageFile);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Deconstructed</title>
</head>
<body>
<header>
<div class="menu">
<nav>MENU</nav>
</div>
</header>
<main class="main-container">
<div id="cover"></div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Mauris pellentesque
pulvinar pellentesque habitant morbi tristique senectus et netus. Lectus
proin nibh nisl condimentum id venenatis a condimentum. Id diam maecenas
ultricies mi eget mauris.
</div>
</main>
<!-- CUSTOM SCRIPTS -->
<script src="script.js"></script>
</body>
</html>