Home > Enterprise >  Multiple Identical Divs to only change url image
Multiple Identical Divs to only change url image

Time:01-09

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 >
     <div >
          <a ><img src="images/im.jpg" alt="Image" ></a>
         <div>
             <h3 ><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?

CodePudding user response:

Example

The example works by having a data object, which stores the captions and image URLs. Then, there is a clone template. It loops through each and clones the template, and replaces each element with the correct content. Then it adds it to the HTML with .appendChild.

CodePudding user response:

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 >
        <div >
             <a ><img src="images/im.jpg" alt="Image" ></a>
            <div>
                <h3 ><a href="#">Us</a></h3>
            </div>
        </div>
   </div>
</div>

<button onClick="copyAndChangeImageAndCaption()">Add images</button>

  •  Tags:  
  • Related