14.15 Removing Body Content
NN 6, IE 5
14.15.1 Problem
You want to eliminate an element or
portion of text from the current document.
14.15.2 Solution
If you have a reference to the element you wish to delete, you can
use the W3C DOM removeChild( ) method to remove
the element. The method works only on child nodes, so you must step
outward to the element's parent to invoke the
method:
var elem = document.getElementById("spanToGo");
elem.parentNode.removeChild(elem);
To eliminate text from a text node, set its node value to an empty
string:
var container = document.getElementById("someSpan");
// verify that the child node is a text node before emptying it
if (container.firstChild.nodeType = = 3) {
container.firstChild.nodeValue = "";
}
To remove the text node entirely, use the removeChild(
) method as shown above for the element
node removal.
14.15.3 Discussion
When you remove repetitive elements, such as rows of a table, you may
need to iterate through a collection when appropriate. For example, a
table or tbody element object
has a rows property that returns a collection of
all tr element objects nested within. If you
intend to remove all the rows, it is more efficient to remove them
via a tight while loop, acting on the first child
until there are no more children:
var tbody = document.getElementById("myTableBody");
while (tbody.rows.length > 0) {
tbody.removeChild(tbody.firstChild);
}
But if removal among a collection is meant to be selective, you also
have to account for a changing collection of numeric indexes for the
collection's array while the array gets smaller. To
work around this potential problem, use a for loop
that starts at the end and decrements the index counter so that the
counter doesn't get off track with a changing
collection.
For an example of selective deletion in action, consider the
following table, in which each row contains a checkbox and some text.
A button at the bottom of the table deletes any and all rows in which
the checkbox is checked. The HTML for the table is as follows:
<form>
<table>
<tbody id="myTBody">
<tr>
<td><input type="checkbox"></td><td>Item 1</td>
</tr>
<tr>
<td><input type="checkbox"></td><td>Item 2</td>
</tr>
<tr>
<td><input type="checkbox"></td><td>Item 3</td>
</tr>
<tr>
<td><input type="checkbox"></td><td>Item 4</td>
</tr>
<tr>
<td><input type="checkbox"></td><td>Item 5</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Remove Checked" onclick="remove( )"></td>
</td>
</tr>
</tbody>
</table>
</form>
The remove( ) function is as follows:
function remove( ) {
var elem = document.getElementById("myTBody");
for (var i = elem.rows.length-1; i >= 0 ; i--) {
if (elem.rows[i].cells[0].firstChild.checked) {
elem.removeChild(elem.rows[i]);
}
}
}
You could also use the deleteRow( ) method of the
tbody object in the function.
14.15.4 See Also
Recipe 14.13 for ways to reference elements in the document.
|