+ Start a Discussion
Himanshu Srivastava 52Himanshu Srivastava 52 

I'm using for-each loop and want to highlight a single row in LWC using onmouseover but only the topmost row in the loop is getting highlighted

In this code every time I'm hovering the mouse on a record the topmost row in the component is getting highlighted instead of the corresponding row on which the mouse is hovered. Any suggestion will be appreciated.

HTML file snippet
<template for:each={actions} for:item="action">
            <div class="slds-p-vertical_xxx-small box" key={action.Id} id={action.Id} onmouseover={addColor} onmouseout={removeColor}>
                <div class="slds-p-left_medium">
                    {action.Name}
                </div>
            </div>
</template>

JS File snippet
addColor() {
    this.template.querySelector('.box').classList.add('highlight');
}

removeColor() {
    this.template.querySelector('.box').classList.remove('highlight');
}

CSS File
.highlight {
background-color: rgb(243, 242, 242);
}

Screenshot
User-added image
Here I've my mouse pointed on 'Action 3' record but the 'Action 1' is getting highlighted.
Yogendra JangidYogendra Jangid
Hi Himanshu,
This is because if you go with the documentation of querySelector, it only gets the first element with the class selector. Having said that, this.template.querySelector('.box').classList.add('highlight'); will give you first element i.e. Action 1.
If you really wish to get the interested row, I would suggest you to use dynamic class creation with Id appended and then you will be able to access the exact row. 

Hope this answers your question, if so please can you mark this as best answer.