Ask Your Question
3

How can you delete all elements with a specific ID and their related elements in Javascript, including those further down the hierarchy (using recursion)?

asked 2022-09-01 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-04-29 17:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-01 11:00:00 +0000

Seen: 10 times

Last updated: Apr 29 '22