Home » Jquery » jquery – Find the next section by class name

jquery – Find the next section by class name

Posted by: admin February 22, 2020 Leave a comment

Questions:

How can I show the next div with class form_section by clicking .btn_next?

$(".form_section").hide();

$(document).on("click", ".btn_next", function(e) {
  $(this).next(".form_section").show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row form_section">
  <div>
    <div></div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
<div class="row form_section">
  <div>
    <div></div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
<div class="row form_section">
  <div>
    <div></div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
How to&Answer:

first you need to hide current “.form_section” section (to the button which was clicked), then get the next .form_section to show.

<script>

        //$(".form_section").hide();
        $(document).on("click", ".btn_next", function(e){
            $(this).parents('.form_section').hide();
            $(this).parents('.form_section').next().show();                
        }); 
    </script>

Answer:

To achieve this you need to traverse the DOM to retrieve the nearest parent .form_section to the button which was clicked, hide it, then get the next .form_section to show.

To do that you can use a combination of closest(), hide(), next() and show(). Try this:

$(document).on("click", ".btn_next", function(e) {
  $(this).closest('.form_section').hide().next(".form_section").show();
});
.form_section { display: none; }
.form_section:nth-of-type(1) { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row form_section">
  <div>
    <div>1</div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
<div class="row form_section">
  <div>
    <div>2</div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>
<div class="row form_section">
  <div>
    <div>3</div>
    <div></div>
    <button class="btn btn-primary btn_next">SHOW NEXT SECTION</button>
  </div>
</div>

Note the use of CSS to hide/show the relevant elements when the page loads. This is a better approach than using JS as it avoids the FOUC.