Home > OS >  JS logic for src in a img-tag
JS logic for src in a img-tag

Time:01-19

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:

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

CodePudding user response:

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>
        `
    })

  •  Tags:  
  • Related