jQuery offers a variety of methods that can be used for DOM manipulation.
The first is the .empty() method.
Imagine the following markup:
<div id="content">
<div>Some text</div>
</div>
By calling $('#content').empty();
, the inner div would be removed. This could also be achieved by using $('#content').html('');
.
Another handy function is the .closest() function:
<tr id="row_1">
<td><button type="button" class="delete">Delete</button>
</tr>
If you wanted to find the closest row to a button that was clicked within one of the row cells then you could do this:
$('.delete').click(function() {
$(this).closest('tr');
});
Since there will probably be multiple rows, each with their own delete
buttons, we use $(this)
within the .click() function to limit the scope to the button we actually clicked.
If you wanted to get the id
of the row containing the Delete
button that you clicked, you could so something like this:
$('.delete').click(function() {
var $row = $(this).closest('tr');
var id = $row.attr('id');
});
It is usually considered good practise to prefix variables containing jQuery objects with a $
(dollar sign) to make it clear what the variable is.
An alternative to .closest()
is the .parents() method:
$('.delete').click(function() {
var $row = $(this).parents('tr');
var id = $row.attr('id');
});
and there is also a .parent() function as well:
$('.delete').click(function() {
var $row = $(this).parent().parent();
var id = $row.attr('id');
});
.parent()
only goes up one level of the DOM tree so it is quite inflexible, if you were to change the delete button to be contained within a span
for example, then the jQuery selector would be broken.