How can I parse a document and delete all elements except one that matches the ID and its children

I have a webpage with many nested divs. How can I remove all elements except 1, which has a specific ID and its children.

I want to keep this div and its children and delete everything else, even its parents

The following code does not work, it also removes children

var elms = document.getElementsByTagName('*'); for (var i = 0; i < elms.length; i++) { if (elms[i].id != "div63") { elms[i].parentNode.removeChild(elms[i]) } }; 

I need a solution other than jQuery.

+4
source share
2 answers

You can save the link to your node, delete everything, and then put your node in the body:

 var saved = document.getElementById('div63'); var elms = document.body.childNodes; while (elms.length) document.body.removeChild(elms[0]); document.body.appendChild(saved); 

Demonstration

+3
source

A somewhat alternative approach to the one provided by dystroy is that the following moves the element you want to keep, placing it as the first child of the parent from which you want to remove all other child elements (the body element is used by default if the parent not provided), unlike the alternative β€œdelete everything and then return” approach. After moving this, it removes all subsequent child nodes from this parent (this includes a rather ugly function to extract this element, although it did not try to compensate for the absence of document.querySelector() in browsers without this function)):

 function retrieveElem(ref) { if (!ref) { return document.body; } else { if (typeof ref === 'string') { if (document.querySelector) { var dQSresult = document.querySelector(ref); if (dQSresult) { return dQSresult; } else { return document.querySelector('#' + ref); } } } else { switch (ref.nodeType) { case 1: // it an element return ref; case 9: // it the document node return document.body; } } } } function clearAllExcept(el, from) { el = retrieveElem(el); from = retrieveElem(from); from.insertBefore(el, from.firstChild); while (from.firstChild.nextSibling) { from.removeChild(from.firstChild.nextSibling); } } clearAllExcept('#id63','.aChild'); 

JS Fiddle demo .

This can be called, as indicated above, using CSS selector strings or as follows:

 // with a CSS selector to identify the `id` of the child clearAllExcept('#id63'); 

JS Fiddle demo .

 // with a string to identify the `id` of the child clearAllExcept('id63'); 

JS Fiddle demo .

 // with a node-reference to the child: clearAllExcept(document.getElementById('id63')); 

JS Fiddle demo .

Similar selectors can be used to identify the parent, as well as:

 // using the `document`: clearAllExcept('#id63', document); 

JS Fiddle demo .

 // with a string to identify the `id` of the parent clearAllExcept('#id63','#test'); 

JS Fiddle demo .

 // with a node-reference to the parent: clearAllExcept('#id63', document.getElementById('test')); 

JS Fiddle demo .

Literature:

+1
source

All Articles