简体   繁体   中英

How can I remove the next div of the parent of an element?

 function yes(event, yesicon) { event.stopPropagation(); yesicon.closest('button').nextSibling.remove(); //Why doesn't this work??? yesicon.closest('button').remove(); //This works ok } 
 <div class="doors_list" id="doors_list"> <button class="accordion"> <div> <img src="Iconos/arrow_down.png" alt="Expand" class="arrow_icon"> </div> <div> <img src="Iconos/yes.png" onclick="yes(event,this);" alt="Yes" class="yes_icon"> </div> <div> <p class="door_room">Kitchen</p> </div> </button> <div class="panel"> --THIS IS THE ONE I WANT TO DELETE -- <p>Info on Door 1</p> </div> </div> 

Inside doors_list I actually have several buttons of class 'accordion' followed by the div of class 'panel' which is the one I want to delete for each one when the 'yes' icon is clicked.

What I want to do is to remove the next div of the class 'panel' with the "yes" function.

yesicon.closest('button') seems to be working ok but when I want to remove the nextSibling it doesn't seem to work.

You have invalid HTML and that is the cause of your problem.

Leaving aside the issue that a <div> is not allowed inside a <button> in the first place…

The content of the button is:

  • Start div
  • img
  • End div
  • img
  • End div

Since there is no open div for the second end tag to close, error recovery implicitly closes the button, and then the div end tag closes the doors_list element.

Consequently: The element you are aiming for is not a sibling of the button, but of its parent.

Use a validator . Write valid HTML.

You want to use nextElementSibling as it will, as its name implies, be the next sibling element. nextSibling will be whatever node follows, and in your case is going to be a text node: the white space characters between your elements.

 function yes(event, yesicon) { event.stopPropagation(); yesicon.closest('button').nextElementSibling.remove(); } 
 <div class="doors_list" id="doors_list"> <button class="accordion"> <div> <img src="Iconos/arrow_down.png" alt="Expand" class="arrow_icon" /> </div> <div> <img src="Iconos/yes.png" onclick="yes(event,this);" alt="Yes" class="yes_icon" /> </div> <div> <p class="door_room">Kitchen</p> </div> </button> <div class="panel"> --THIS IS THE ONE I WANT TO DELETE -- <p>Info on Door 1</p> </div> </div> 

You forgot to open the div before your icon

</div>
 <img src="Iconos/yes.png" onclick="yes(event,this);" alt="Yes" class="yes_icon">
</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