简体   繁体   中英

How to Delete a Specific Child Node

I have the following Code

 <script> function delete(){ var e = document.getElementById('parent'); e.removeChild(e.children[0]); } </script>
 <div id="parent"> <div id="child"> <input type="text" placeholder="name"> <button onclick="delete()"> delete</button> </div> <div id="child"> <input type="text" placeholder="age"> <button onclick="delete()"> delete</button> </div> </div>

When I press the delete button, the first child node gets deleted. However, I want to delete only the specific child node. For example: if I click the delete button in the name input field only the name input field should be deleted.

this is fully working example.

 function deleteNode(item){ item.parentNode.remove() }
 <div id="parent"> <div id="child"> <input type="text" placeholder="name"> <button onclick="deleteNode(this)"> delete</button> </div> <div id="child"> <input type="text" placeholder="age"> <button onclick="deleteNode(this)"> delete</button> </div> </div>

Look at these two lines:

var e = document.getElementById('parent');    
e.removeChild(e.children[0]);

here you are getting an element by its id, and the id is 'parent'. This will always give you the div.

Then you delete the first child of e.

You need a different method of getting the element to delete!

A first step would be to look at the target of your event handler:

   function delete(ev){
     var target = ev.target;
     console.log("the element that was clicked is ", target);
     // continue from here
   }

First and foremost, delete is a reserved keyword you cannot use it for a function name.

Secondly, you must pass a reference of the element being clicked. This can be achieved by passing the this argument to your onclick handler:

<button onclick="deleteParent(this)"> delete</button>

This will result in the following

 <div id="parent">
     <div>
      <input type="text" placeholder="name"> 
      <button onclick="deleteParent(this)"> delete</button>
     </div>

     <div>
      <input type="text" placeholder="age"> 
      <button onclick="deleteParent(this)"> delete</button>
     </div>
 </div>

 <script>
   function deleteParent(btn){
     btn.parentNode.remove();
   }
 </script>

You should also not use the same id on multiple elements.

try this:

function delete(){
    $(this).parent().remove()
}

and you can't use same id for different div

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