Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS logic for src in a img-tag

I’m fetching data, text and imageUrl from an API. In the case there are no imageUrl returned I want to display a image from my assets folder instead.

Can I write the logic inside the img-tag and if so how? or do I have to write some function outside?

This is how to code looks now:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

profiles.forEach((profile) => {
        expertiseContainer.innerHTML += `
        <div >
            <img src="${ profile.imgUrl }" alt="Profile image">
            <h2>${ profile.name }</h2>
        </div>
        `
    })

>Solution :

One approach is below, using a conditional operator within the template-string:

profiles.forEach((profile) => {
        expertiseContainer.innerHTML += `
        <div >
            <img src="${ profile.imgUrl ? profile.imgUrl : 'assets/default.png' }" alt="Profile image">
            <h2>${ profile.name }</h2>
        </div>
        `
    })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading