0

I am findiing Divs dynamically in my LWC component using data-id and that works. But when i am trying to set background image, it says.cannot read of property style of undefined. here is my code:

  wiredResult({
    error,
    data
}) {
    if (data) {
      
       this.result=data;
     
      for(var i=0;i<this.result.length;i++)
      {
        console.log('RESULTID'+this.result[i].Id);
         this.target = this.template.querySelectorAll("[data-id="+this.result[i].Id+"]");
         console.log('target'+this.target);
         this.target.getelement().style.backgroundImage= this.result[i].Offer_Image__c; 
      }

any hrlp wil be appreciated.

3 Answers 3

0

This may answer your question, you can test it in this playground playground

@sfdcfox did you share all code? otherwise, how do we get the event?

    contacts;

    renderedCallback() {
        this.setBackgroundImage();
    }

    setBackgroundImage() {

        const divs = this.template.querySelectorAll('div');

        if (divs) {

            this.contacts.map((contact) => {

                const div = Object.values(divs).filter(div => (div.getAttribute('data-id') === contact.Id))[0];
                div.style.backgroundImage = `url(${contact.Offer_Image__c})`;
            });

        }
    }

0

You need to update the property so it is wrapped in the url syntax required by CSS:

event.target.style.backgroundImage = `url(${this.result[i].Offer_Image__c})`; 

Also, getelement is not required, as demonstrated above.

0

Use the background-image in the getter.

JavaScript

import { LightningElement, track } from 'lwc';

export default class App extends LightningElement {
   get image(){
       return `background-image: url("https://amymhaddad.s3.amazonaws.com/morocco-blue.png");
    height: 400px;
    width: 100%;`

   }
}

HTML

<template>
    <div style={image}></div>
</template>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .