Home > Net >  How remove a div generated from a foreach loop after clicking in 'X'
How remove a div generated from a foreach loop after clicking in 'X'

Time:12-29

i´m using MVC and I have a page where the info was generated from a foreach loop, tha shows the model´s property.

 @foreach (var chassi in Model.Chassis)
                {
                    <div >
                        @chassi
                        <img src="~/assets/icons/exclude.svg" alt="Remove chassis"/>
                    </div>
                }

image

I have to do this 'X' works, to remove this div and remove the info from the model that this page is receving.

CodePudding user response:

You can achieve this by following these steps:

  • Assign id to each div element via the same loop.
  • Add onclick handler to img element.
  • This handler, when clicked on image icon, will give you access to the event.
  • Access the desired div by calling event.target.parentNode and make its display property none to hide it or call remove() to remove it from the dom.

Hope this helps.

CodePudding user response:

Can try something like this (you can merge the JS in the onclick with your delete image):

<div >
  Test
  <button onClick="this.parentNode.parentNode.removeChild(this.parentNode);">Delete me</button>

</div>
<div >
  Test
  <button onClick="this.parentNode.parentNode.removeChild(this.parentNode);">Delete me</button>

</div>

CodePudding user response:

just remove the parent

<img onclick="remove(this.parentNode);" />

or if you have multi parent

<img onclick="remove(this.parentNode.parentNode);" />
  • Related