Object doesn’t support Property or method 'prepend'

Asked

Viewed 241 times

0

I am trying to make my WEB application compatible with Edge Browser. But I get the message "Object doesn’t support Property or method 'prepend'" on the console when I try to run the following code:

    var li = document.createElement("li");
 ...
    var list = document.getElementById("history");
    if (this.stackHistory.size() === 0) {
        list.innerHTML = "";
        list.appendChild(li);
    } else {
        if (document.getElementById("historyorder").value === "last")
           list.prepend(li); //ERROR AQUI
        else
           list.appendChild(li);
}

Such code worked on Google Chrome and Firefox

1 answer

4


The method prepend which you have specified is not supported in Edge browser or IE.

This is something you can confirm in the documentation compatibility section

However, you may use polyfill that the documentation itself indicates:

(function (arr) {
  arr.forEach(function (item) {
    if (item.hasOwnProperty('prepend')) {
      return;
    }
    Object.defineProperty(item, 'prepend', {
      configurable: true,
      enumerable: true,
      writable: true,
      value: function prepend() {
        var argArr = Array.prototype.slice.call(arguments),
          docFrag = document.createDocumentFragment();

        argArr.forEach(function (argItem) {
          var isNode = argItem instanceof Node;
          docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
        });

        this.insertBefore(docFrag, this.firstChild);
      }
    });
  });
})([Element.prototype, Document.prototype, DocumentFragment.prototype]);

Link to this polyfill on github

The polyfill above stated is the code that will add "to the browser" to the function prepend if it does not support it. For this reason it must be executed before the code that uses the prepend.

  • @dvd O polyfill not to add an element is to add the function prepend "to the browser" causing prepend will still work on IE and Edge. Note that I did not "invent" this code. It is at the end of the MDN documentation page linked in my reply. I simply put here to add more relevant content to the answer.

  • @dvd The advantage of using polyfill is that in this case you can use pure JS code and work in all browsers, even if it is a recent function like prepend. The only peculiarity is that you have to call this code polyfill once at the beginning of page loading, which can even be in a file only included with polyfills for example. Soon it seems actually worse than it is

Browser other questions tagged

You are not signed in. Login or sign up in order to post.