使用JS達到移除元素的效果有兩種方式

1.使用CSS隱藏元素

var elem = document.querySelector('#some-element');
elem.style.display = 'none';


2.removeChild()
如果你想從DOM中完全移除元素可使用removeChild()

var elem = document.querySelector('#some-element');
elem.parentNode.removeChild(elem);


remove()
ES6新方法remove()

var elem = document.querySelector('#some-element');
elem.remove();

remove()支援現代瀏覽器,但不支援IE,可使用polyfill使它支援到IE9

/**
* ChildNode.remove() polyfill
*/
// from:https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
(function (arr) {
arr.forEach(function (item) {
if (item.hasOwnProperty('remove')) {
return;
}
Object.defineProperty(item, 'remove', {
configurable: true,
enumerable: true,
writable: true,
value: function remove() {
this.parentNode.removeChild(this);
}
});
});
})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);


REFERENCE: Go Make Things

arrow
arrow
    文章標籤
    removeChild() remove()
    全站熱搜
    創作者介紹
    創作者 浣熊 的頭像
    浣熊

    前端生涯

    浣熊 發表在 痞客邦 留言(0) 人氣()