轉(zhuǎn)載自:《原生JavaScript實(shí)現(xiàn)remove()刪除和recover()恢復(fù)元素》
利用原生JavaScript實(shí)現(xiàn):
1荷荤、remove(selectors)刪除指定的一個(gè)或一組元素。
2、recover(selectors)恢復(fù)剛才刪除的元素血久。
function remove(selectors) {
selectors.removeNode = [];
if (selectors.length != undefined) {
var len = selectors.length;
for (var i = 0; i < len; i++) {
selectors.removeNode.push({
parent: selectors[i].parentNode,
inner: selectors[i].outerHTML,
next: selectors[i].nextSibling
});
}
for (var i = 0; i < len; i++)
selectors[i].parentNode.removeChild(selectors[0]);
}
else {
selectors.removeNode.push({
parent: selectors.parentNode,
inner: selectors.outerHTML,
next: selectors.nextSibling
});
selectors.parentNode.removeChild(selectors);
}
}
function recover(selectors) {
var len = selectors.removeNode.length;
for (var i = 0; i < len; i++) {
var node = selectors.removeNode[i];
if (node.next == null)
node.parent.innerHTML += node.inner;
else {
var div = document.createElement("div");
div.innerHTML = node.inner;
node.parent.insertBefore(div.childNodes[0], node.next);
}
}
}