Home > Back-end >  Trying to insert an image dynamically to a template fragment
Trying to insert an image dynamically to a template fragment

Time:04-17

I am trying to insert an image through the backend using a URL pulled from a database and attempting to dynamically display them based on an expense that a user wants to see when they click the how more button. I am new to remplates so i'm struggling to understand the syntax and process of using this

Show More Button displayed in the template of HTML page

showMoreBtn.innerText = 'Show More'
                showMoreBtn.addEventListener('click', () => {
                // const img = document.createElement('img')
                // img.src = `uploads/${exp.expFile}`
                // img.src = 'uploads/user2-165015.jpeg'
                console.log('exp File Path', exp.expFile)
                })

Template code used in the HTML file

</template>
    <template id="expList">
        <section >
            <h1 id="expID"></h1>
            <h2 id="expLabel"></h2>
            <p><button  ></button></p>
            <!-- <img id="expImage" src="uploads/user2-1650152674035.jpeg" width="400" height="300"> -->
            </section>
    </template>

The question would be how would i dynamically insert these images from paths taken from a database as its tricky with templates. any help is appreciated. Thanks

CodePudding user response:

First you need to get your section element:

const section = document.querySelector(".expSection");

And then to add it to your page you need to:

section.appendChild(img);
  • Related