0

I'm trying to add/remove a class from a "great-great-grandparent" div.

In general, if I click on a div with class 'slds-media', I want to add the 'slds-is-open' class to the 'my-section' div which is four levels above it.

the markup is as follows:

<div class="slds-summary-detail my-section"> <!-- I want to add a new class here -->
    <button class="slds-button"></button>
    <div class="sldx...">
        <div class="sldx...">
            <div class="sldx...">
                <div class="slds-media"> <!-- when clicking within this div>
                ...
                ....

JS:

import { LightningElement } from 'lwc';

  export default class AddProductWizard extends LightningElement {

    renderedCallback(){
        var sections = this.template.querySelectorAll('.slds-media');
        for (let index = 0; index < sections.length; index++) {
            sections[index].addEventListener('click',this.openCloseSection); //add click event to each section to open or close it 
        }

    }

    openCloseSection(){
        let parentClassList = this.closest(".my-section").classList;
        parentClassList.contains('slds-is-open') ? parentClassList.remove('slds-is-open') : parentClassList.add('slds-is-open');
    }                
}

So I added a click event to all the elements with class 'slds-media', and now I want to get their great-great grandparent to see if the 'slds-is-open' exists or not.

I get the following error:

Uncaught TypeError: this.closest is not a function

1 Answer 1

3

The "this" pointer in an LWC function is the LWC component. If you want the element that was clicked, you need to update the method thus:

openCloseSection(event) {
    let parentClassList = event.target.closest(".my-section").classList;
    ...
}

You must log in to answer this question.

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