Delete element

2 snippets across 2 stacks - JavaScript, Python

Also written as remove element

JSJavaScript

Removing Elements

JS · DOM Manipulation
Syntax
element.remove()
parent.removeChild(child)
Example
// Modern: element removes itself
const notification = document.querySelector(".notification");
notification.remove();

// Remove all children
const container = document.querySelector("#list");
while (container.firstChild) {
  container.removeChild(container.firstChild);
}

// Faster: clear all children
container.replaceChildren();

Note el.remove() is cleaner than parentNode.removeChild(el). Use replaceChildren() with no arguments to efficiently clear all children.

PYPython

remove, pop, del, clear

PY · Lists
Syntax
list.remove(value)
list.pop(index)
del list[index]
Example
items = ["a", "b", "c", "d", "e"]
items.remove("c")
print(items)
last = items.pop()
print(last, items)
del items[0]
print(items)
Output
['a', 'b', 'd', 'e']
e ['a', 'b', 'd']
['b', 'd']

Note remove() deletes the first matching value (raises ValueError if missing). pop() removes by index and returns the value. del removes by index without returning.

Frequently asked questions

How do you delete element?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Removing Elements" snippet in JavaScript uses `element.remove()`.
Which code does the JavaScript example use?
The "Removing Elements" snippet uses `element.remove()`, from the DOM Manipulation section of the JavaScript cheat sheet.
Which stacks cover "delete element" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Removing Elements": el.remove() is cleaner than parentNode.removeChild(el). Use replaceChildren() with no arguments to efficiently clear all children.