The delete()
method of the IDBObjectStore
interface returns an IDBRequest
object, and, in a separate thread, deletes the specified record or records.
Either a key or an IDBKeyRange
can be passed, allowing one or multiple records to be deleted from a store. To delete all records in a store, use IDBObjectStore.clear
.
Bear in mind that if you are using a IDBCursor
, you can use the IDBCursor.delete()
method to more efficiently delete the current record — without having to explicitly look up the record's key.
An IDBRequest
object on which subsequent events related to this operation are fired.
If the operation is successful, the value of the request's result
property is undefined
.
This method may raise a DOMException
of the following types:
-
TransactionInactiveError
DOMException
-
Thrown if this object store's transaction is inactive.
-
ReadOnlyError
DOMException
-
Thrown if the object store's transaction mode is read-only.
-
InvalidStateError
DOMException
-
Thrown if the object store has been deleted.
-
DataError
DOMException
-
Thrown if key
is not a valid key or a key range.
The following code snippet shows the deleteItem()
function, which is part of the To-do Notifications example app. This app stores to-do list items using IndexedDB. You can see the app's complete code on GitHub, and try out the app live.
The deleteItem()
function is called when the user clicks the button to delete a to-do list item. The item key is set in the button's 'data-task'
data attribute, so the function knows which item to delete. The function opens a database transaction in which to delete the item, supplying its key. When the transaction completes, the function updates the app UI to report that the item was deleted.
Note that in this function db
is a global variable referring to an IDBDatabase
object that is initialized when the app loads.
function deleteItem(event) {
let dataTask = event.target.getAttribute("data-task");
let transaction = db.transaction(["toDoList"], "readwrite");
let request = transaction.objectStore("toDoList").delete(dataTask);
transaction.oncomplete = () => {
event.target.parentNode.parentNode.removeChild(event.target.parentNode);
note.innerHTML += `<li>Task "${dataTask}" deleted.</li>`;
};
}