What's the difference between child.remove () and parent.removeChild (child)?

The only link I could find in the javascript function remove()

is this page on w3schools, which claims to have a method to remove options from selections. However, it clearly works as expected when I call it on any node when I test it in Chrome and Firefox.

Has it been updated? I've always had to do something like child.parentNode.removeChild(child)

in the past. Are there any advantages / disadvantages for using one over the other?

+3


source to share


2 answers


HTMLElement

the object has a remove

method. This method only supports modern browsers. It removes the html element.



What you mean is HTMLSelectElement

(which implements the HTMLElement

interface object) an object remove

that removes option

by index. The method is supported by both old and new browsers. Without passing the index, the element itself is select

deleted.

+2


source


Looking at the spec, they seem to be doing the same thing.

https://dom.spec.whatwg.org/#dom-childnode-remove

The remove () method, when called, should do the following:

If the context objects are null, complete these steps.

Remove the context object from the parent context objects.

The last line seems to suggest doing this anyway child.parentNode.removeChild (child).

https://dom.spec.whatwg.org/#dom-node-removechild



The removeChild (child) method must return the result of previously removing the child from the context object.

https://dom.spec.whatwg.org/#concept-node-pre-remove

To pre-remove a child from a parent, follow these steps:

If the parent parent is not the parent, throw a NotFoundError exception. Remove the child from the parent.

Returns the child element.

As for, if there is an advantage for one over the other, I'm not sure if there is one. (Maybe, maybe, but I couldn't find anything). It probably just depends on what is best for readability in your context.

0


source







All Articles