0

I'm trying to change the background color of the selected row in a table, but having some issues with it.

I'm trying to select the row and catch it with event, and later change the color for the event.target

a little help will be much appreciated.

this is my HTML:

   <div class="products-row tableHeader">
      <div class="products-cell" key={col.label} for:each={testColObj} for:item="col">{col.label}</div>
   </div>

  <div class="products-row" key={rowItem.Account.Id} for:each={testObjData} for:item="rowItem" data-id={rowItem.Account.Id}>
    <div class="products-cell">
         <input
             type="radio"
             name="selectedRow"
             value={choseSelected}
             id={rowItem.Account.Id}
             onchange={changeChoose}/>
      </div>
      <div class="products-cell">
       <span>{rowItem.Account.Id}</span>
      </div>
      <div class="products-cell">
       <span>{rowItem.Account.Name}</span>
      </div>
      <div class="products-cell">
       <span>{rowItem.Account.Industry}</span>
      </div>
 </div>

And my JS is:

 changeChoose(event){
        console.log(event.target.id);    
        this.choseSelected = event.target.id;
        event.target.style.backgroundColor ='blue';

    }

On the developer console, when I'm changing the products-row for the specific row in the HTML, it works, but I'm not sure how to apply it in the JS file.

Many thanks!

1 Answer 1

0

Please try below code where we can use currentTarget to get the value of clicked div & query the element to set its css properties:

changeChoose(event){
   console.log(event.target.id);    
   this.choseSelected = event.target.id;
   this.template.querySelector(`[data-id="${event.currentTarget.dataset.id}"]`).style.background = "blue"; 
}

There's a nice stack exchange answer about currentTarget VS target.

Although above code will work , I would prefer to use js add method to add(or toggle method as per your requirement) css classes using below approach :

changeChoose(event){
    console.log(event.target.id);    
    this.choseSelected = event.target.id;
    const selectedDiv = this.template.querySelector(`[data-id="${event.currentTarget.dataset.id}"]`);

     if(selectedDiv) {
        selectedDiv.classList.add("background-cls");
     }
}

In css file for LWC , add a class as below :

.background-cls {
 background-color: blue;
}

Also , you would need handling for previously selected divs as per my understanding.

You must log in to answer this question.

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