Home > Software design >  How to affect specific element with jQuery toggleClass
How to affect specific element with jQuery toggleClass

Time:07-29

I'm doing a side-navbar, it has multiple link containers that are suppoused to be hidden until a click event happens on the link-title above it. The code is something like this:

<div >
     <small >Utilities</small>
     <div  data-type="accounts">
       <span  data-icon="material-symbols:inventory-2-outline-rounded" style="color: #ececec;" data-width="20" data-height="20"></span>
       <p>Accounts</p>
     </div>
     <div >
       <p>manage</p>
       <p>example</p>
       <p>example</p>
       <p>example</p>
       <p>example</p>
     </div>
</div>

When I click on the element link-section-title, I'm using jQuery to toggle a class called 'open' that sets a max-height to the div.links. The problem is that I have multiple link-sections and everytime I click on one link-section-title it adds the open class to every div.links in the page.

Is there some way to prevent this and only add the class to the container that is suppoused to open? Thanks.

CodePudding user response:

Use $(this) to access the elements in the same section.

$(".link-section-title").click(function() {
    $(this).siblings(".links").toggleClass("open");
});
  • Related