Here is a function that uses recursion to delete all elements with a specific ID and their related elements:
function deleteElementsById(id) {
var element = document.getElementById(id);
if (element) {
var parent = element.parentNode;
parent.removeChild(element);
// Recurse through all child nodes and delete them as well
var children = element.childNodes;
for (var i = 0; i < children.length; i++) {
var child = children[i];
deleteElementsById(child.id);
}
}
}
To use this function, simply call deleteElementsById(id)
with the ID of the element you wish to delete. This will remove the element from the DOM and recursively delete any child elements with the same ID.
Asked: 2022-09-01 11:00:00 +0000
Seen: 10 times
Last updated: Apr 29 '22