Remove element by id

2018-12-31 02:38发布

When removing an element with standard JavaScript, you must go to its parent first:

var element = document.getElementById("element-id");
element.parentNode.removeChild(element);

Having to go to the parent node first seems a bit odd to me, is there a reason JavaScript works like this?

标签: javascript
16条回答
还给你的自由
2楼-- · 2018-12-31 03:13

You could make a remove function so that you wouldn't have to think about it every time:

function removeElement(id) {
    var elem = document.getElementById(id);
    return elem.parentNode.removeChild(elem);
}
查看更多
柔情千种
3楼-- · 2018-12-31 03:13

you can just use element.remove()

查看更多
琉璃瓶的回忆
4楼-- · 2018-12-31 03:14

It's what the DOM supports. Search that page for "remove" or "delete" and removeChild is the only one that removes a node.

查看更多
闭嘴吧你
5楼-- · 2018-12-31 03:18

According to DOM level 4 specs, which is the current version in development, there are some new handy mutation methods available: append(), prepend(), before(), after(), replace(), and remove().

http://red-team-design.com/removing-an-element-with-plain-javascript-remove-method/

查看更多
登录 后发表回答