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:
source share