Scoping JavaScript: How to operate only on specific elements?
P粉884548619
P粉884548619 2023-09-08 20:36:06
0
1
629

I have a very simple JS code that only does one thing, which is to toggle an open class on a specific element on the page. The problem is, I have 4 duplicate .clickSlide elements and .sub_menu elements, and when I click on one of them to trigger the tag, all the elements get open kind. Only one of the focused elements should get the open class.

My best guess is that something this is missing in the JS. But I'm open to solutions to this problem!

jQuery(document).ready(function($) {
  $(".clickSlide").click(function() {
    $(".sub_menu").toggleClass("open");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ht_course_one">
  <ul class="select-menu dropdown">
    <li class="clickSlide">
      <ul class="sub_menu">
        <li></li>
      </ul>
    </li>
  </ul>
</div>

<div class="ht_course_two">
  <ul class="select-menu">
    <li class="clickSlide">
      <ul class="sub_menu">
        <li></li>
      </ul>
    </li>
  </ul>
</div>

<div class="ht_course_three">
  <ul class="select-menu">
    <li class="clickSlide">
      <ul class="sub_menu">
        <li></li>
      </ul>
    </li>
  </ul>
</div>

<div class="ht_course_four">
  <ul class="select-menu">
    <li class="clickSlide">
      <ul class="sub_menu">
        <li></li>
      </ul>
    </li>
  </ul>
</div>

P粉884548619
P粉884548619

reply all(1)
P粉431220279

So the solution (based on Anass Kartit's answer) is this:

jQuery(document).ready(function($) {
    $(".clickSlide").click(function(){
        $(this).children(".sub_menu").toggleClass("open");
    });
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template