Search code examples
javascriptarrayssplice

Splice is not a function error


I am getting the error tweetParentsArray.splice is not a function at injectFactCheck

function injectFactCheck(){
    var index = 5;
    var tweetParentsArray = document.getElementsByClassName("js-stream-tweet");
    if(tweetParentsArray.length == 0){return;}
    tweetParentsArray.splice(0, index);

When I console.log the tweetParentsArray it appears to be a normal array to me so I am not sure as to why this function would not exist on this object.


Solution

  • document.getElementsByClassName returns HTMLCollection which is not an array. You can use Array.prototype.slice.call(htmlCollection) to convert it to array and then perform further calculation with array.

    function injectFactCheck(){
      var index = 5;
      var htmlCollection = document.getElementsByClassName("js-stream-tweet");
      var tweetParentsArray = Array.prototype.slice.call(htmlCollection);
      if (tweetParentsArray.length == 0){return;}
      tweetParentsArray.splice(0, index);
    }
    

    See more in this question: Most efficient way to convert an HTMLCollection to an Array