Remove element from html list using javascript

0
263

Introduction:

Remove element from html list using java script . Many times we need to remove some items from list on button click event or hyperlink click event.

Step 1:

Create one html page with bellow code. I am going to create list using for loop which contains li tag including dynamic id like remove_No where No is position of number. In hyperlink on-click event I am passing position of that & in java script on click event I am just removing that particular element.For more information check bellow code

Step 2:

@{
  Layout = null;
}
<!DOCTYPE html>
<html lang="en">
  <head>		
  </head>
  
  <body>
    <div style="margin-left:40px">
      <div>
        <h3>Remove element from list using javascript </h3>
  
        @using (Html.BeginForm())
        {
          for(var i =0; i< 11; i++)
            {
            <li id="remove_@i">
                                 
             <a href="javascript:void();" onclick="Remove(@i)">Remove at postion @i</a>
            
            </li>
            }

        }				
      </div>
    </div>
    <!-- JS includes -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>	
    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>		
    <script type="text/javascript">
      function Remove(Id) { 				
          $('#remove_' + Id).remove();
          
         }
    </script>
  </body>
</html>

Step 3:

Now run the application.


Click to remove item no 3,4 & 7 then output will look like

LEAVE A REPLY

Please enter your comment!
Please enter your name here