jQuery: Delete all table rows except first one using jQuery
jQuery Practical exercise Part - I : Exercise-33
Delete all table rows except first one using jQuery.
Sample Solution:
HTML Code :
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Delete all table rows except first one using jQuery.</title>
</head>
<body>
<table border="1" id="myTable">
<tr>
<th>Year</th>
<th>Savings</th>
</tr>
<tr>
<td>2014</td>
<td>$10000</td>
</tr>
<tr>
<td>2015</td>
<td>$8000</td>
</tr>
<tr>
<td>2016</td>
<td>$9000</td>
</tr>
</table>
<p>
<input id="button1" type="button" value="Click to remove all rows except first one"/></p>
</body>
</html>
JavaScript Code:
$(document).ready(function(){
$('#button1').click(function(){
$("#myTable").find("tr:gt(0)").remove();
});
});
See the Pen jquery-practical-exercise-33 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Set background-image using jQuery CSS property.
Next: How to get the selected value and currently selected text of a dropdown box using jQuery?.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics