Search code examples
javascriptjqueryecmascript-5

remove any child element after certain div index by javascript or jquery


i have this html collection, i want if i click on any div class ".sday" any other div that are present after that be remove .

for example if we click on sday 2 we should keep sday1 and sday 2, and 3 and 4 must delete

my script removing count is ok but it delete wrong div.

any idea?

<div id="parent" class="parent">
    <div class="room-sheet">
      <div class="sday">1</div>
    </div>
    <div class="room-sheet">
      <div class="sday">2</div>
    </div>
    <div class="room-sheet">
      <div class="sday">3</div>
    </div>
    <div class="room-sheet">
      <div class="sday">4</div>
    </div>
</div>

script(using jquery)

<script>
  $(".sday").click(function(){
    console.log("hello");

    var parentElement = $(this).parent().parent().find('.room-sheet');
    var parentChildernCount = $(this).parent().parent().find('.room-sheet').length;
     var elementIndex = $(this).closest('.room-sheet').index();

     var dd = parentChildernCount - elementIndex;

     for(let i=elementIndex; i < dd; i++){
                //note: make sure any element after our index in deleted!!!
                $("#parent").find('.room-sheet').children().eq(i).remove();
            }
  })
</script>

Solution

  • Listen for clicks on a .sday on the parent, navigate to the parent of the clicked .sday (a .room-sheet), call nextAll to get all subsequent siblings, and .remove() them:

    $('#parent').on('click', '.sday', function() {
      $(this).parent().nextAll().remove();
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="parent" class="parent">
      <div class="room-sheet">
        <div class="sday">1</div>
      </div>
      <div class="room-sheet">
        <div class="sday">2</div>
      </div>
      <div class="room-sheet">
        <div class="sday">3</div>
      </div>
      <div class="room-sheet">
        <div class="sday">4</div>
      </div>
    </div>

    Also, there's no need to require a big library like jQuery for something this simple, you may implement this with native DOM methods, if you like:

    document.querySelector('#parent').addEventListener('click', ({ target }) => {
      if (!target.matches('.sday')) {
        return;
      }
      const sheet = target.parentElement;
      while (sheet.nextSibling) {
        sheet.nextSibling.remove();
      }
    });
    <div id="parent" class="parent">
      <div class="room-sheet">
        <div class="sday">1</div>
      </div>
      <div class="room-sheet">
        <div class="sday">2</div>
      </div>
      <div class="room-sheet">
        <div class="sday">3</div>
      </div>
      <div class="room-sheet">
        <div class="sday">4</div>
      </div>
    </div>