I need to create the polyfill for DOM element delete. Can not understand, what is I making wrong. The deleteElements()
method must delete the current element.
<div>1</div>
<div>2</div>
<div>3</div>
<script>
if (document.documentElement.deleteElements === undefined) {
object.defineProperty(Element.prototype, 'deleteElements', {
get: function() {
var elem = this.firstChild;
delete elem;
return
},
set: function(variable) {
this.firstChild = variable;
}
});
}
var elem = document.body.children[0];
elem.deleteElements(); // <-- call must delete an element
</script>
There are several problems there:
You're defining a property with a getter and setter, then using that property as as function, but the getter doesn't return a function. You almost certainly don't want to use a getter and setter.
As I said in my comment, delete
has nothing to do with removing elements from the DOM. delete
removes a property from an object. It has nothing to do with removing an element from the DOM.
If you want to remove the first child of an element without using the native remove
, you'd do this:
this.removeChild(this.firstChild);
(There's also no need for return
at the end of a function unless you're returning a value.)
If you want define a new method on Element.prototype
, you'd do it like this:
Object.defineProperty(Element.prototype, "deleteElements", {
value: function() {
// ...code here...
},
writable: true, // These are the values for the
enumerable: true, // `remove` property on `Element.prototype`
configurable: true // on browsers that property support it
});