2

I'm just trying to get a simple show/hide experiment running using the code below. It runs fine when the code is outside the SLDS grid. However when I place the div inside a grid column, the console log "test" is displayed but the div remains visible. Am I missing something?? ..Thanks

Component

<aura:component >    
    <lightning:button label="Toggle" onclick="{!c.doInit}"/> 
    <div class="slds-grid">
        <div class="slds-col">
            <div class="slds-box">
                <div aura:id="detailDiv" >
                    <c:ShowHideCmpFilter Message="Detail"/>   
                </div>
            </div>
        </div>        
    </div> 
<aura:component >

CSS

.THIS.toggle {
    display: none;
}

Controller

({
    doInit : function(component, event, helper) {
        console.log("test");        
        var toggleText = component.find("detailDiv");        
        $A.util.toggleClass(toggleText, "toggle");        
    }
})

1 Answer 1

4

Without a space in your CSS, .THIS.some-class refers only to top-level elements. To specify child elements, there needs to be a space:

.THIS .toggle {
    display: none;
}

This will correctly toggle the contents as you expect.

3
  • Beautiful, thanks! ..I remember reading about the space but never really understood the purpose. Now I do :)
    – Jay
    Oct 28, 2017 at 20:33
  • @Jay You'll end up using both methods, depending on if you're selecting top level elements or not, so make sure to remember this.
    – sfdcfox
    Oct 28, 2017 at 20:38
  • The part about .THIS only residing on top-level elements will come up a lot when customizing CSS in Lightning. I believe <aura:component> does not put any sort of wrapper element around your component. As such, if there is more than one top-level node, each will be tagged with that CSS class. Depending on the use case, you may find it makes the most sense to wrap the entire component in a <div> or <span> as appropriate, so that your entire component is one single DOM node inside the parent.
    – Charles T
    Oct 28, 2017 at 22:02

You must log in to answer this question.

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