简体   繁体   中英

How can I remove a specific number of DOM elements on a button click?

I am trying to figure out how to remove the four nearest div elements above a button when it is clicked (along with the div containing the button). I have been trying to use .closest() , but have not had much luck. I will always be removing the button itself and the four elements above the button in the DOM order.

There are multiple sets of rows with the divs below, so I cannot select these elements by class alone.

Example HTML:

//Row 1
<div class="col-2 selectedRow">014</div>
<div class="col-4 selectedRow">Test</div>
<div class="col-2 selectedRow">Special Charge</div>
<div class="col-2 selectedRow">012</div>
<div class="col-2 selectedRow"><input type="button" class="removeCode" value="Remove"></div>

//Row 2
<div class="col-2 selectedRow">012</div>
<div class="col-4 selectedRow">Test 2</div>
<div class="col-2 selectedRow">Other Charge</div>
<div class="col-2 selectedRow">011</div>
<div class="col-2 selectedRow"><input type="button" class="removeCode" value="Remove"></div>

Javascript:

$("form").on('click', '.removeCode', function (event) {
    //Remove the current div container, and the 4 divs above that element in the DOM order.
});

You need to make changes to your HTML file such as:

  1. replace your input element with button and apply same styles as wrapper div .
  2. Surround individual row in a container
  3. On click remove container from which button was clicked

for example:

 $("form .removeCode").click(function(event) { $(this).parent(".container").remove(); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <div class="container"> <div class="col-2 selectedRow">014</div> <div class="col-4 selectedRow">Test</div> <div class="col-2 selectedRow">Special Charge</div> <div class="col-2 selectedRow">012</div> <button type="button" class="col-2 selectedRow removeCode">Remove</button> </div> </div> <div class="container"> <div class="col-2 selectedRow">012</div> <div class="col-4 selectedRow">Test 2</div> <div class="col-2 selectedRow">Other Charge</div> <div class="col-2 selectedRow">011</div> <button type="button" class="col-2 selectedRow removeCode">Remove</button> </div> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM