Hi I'm new to web development and I'm trying to practice by making a small site for my mom!
So basically I have this div that I want to replicate multiple times only changing the image url & the h3 caption.
<div class="col-lg-4 mb-5 col-md-6">
<div class="wine_v_1 text-center pb-4">
<a class="thumbnail d-block mb-4"><img src="images/im.jpg" alt="Image" class="img-fluid"></a>
<div>
<h3 class="heading mb-1"><a href="#">Us</a></h3>
</div>
</div>
</div>
I was thinking of using JavaScript to copy the div as a string to be something like ( pseudocode )
for image.length {
getelementbyid.print (div1 + imageArray(i) + div2 + caption(i) + endofDiv )
}
Would this be possible? Would it make sense to do it this way or is there a more simple way?
You can write a function doing this job. Creating copies of your element and change the attributes corresponding to your new data.
function copyAndChangeImageAndCaption(){
const images = [
{imageUrl: "images/de.jpg", caption: "De"},
{imageUrl: "images/it.jpg", caption: "It"},
{imageUrl: "images/fr.jpg", caption: "Fr"}
];
images.forEach(image => {
const el = document.getElementsByClassName('col-lg-4 mb-5 col-md-6');
let copy = el[0].cloneNode(true)
copy.getElementsByClassName('thumbnail')[0].childNodes[0].src=image.imageUrl;
copy.getElementsByClassName('heading')[0].childNodes[0].innerHTML = image.caption;
document.getElementsByClassName('container')[0].appendChild(copy);
});
}
<div class='container'>
<div class="col-lg-4 mb-5 col-md-6">
<div class="wine_v_1 text-center pb-4">
<a class="thumbnail d-block mb-4"><img src="images/im.jpg" alt="Image" class="img-fluid"></a>
<div>
<h3 class="heading mb-1"><a href="#">Us</a></h3>
</div>
</div>
</div>
</div>
<button onClick="copyAndChangeImageAndCaption()">Add images</button>