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.
-
You are actually getting an Object from getElementsByClassName. Array and Object are two different types.Paul Jerome Bordallo– Paul Jerome Bordallo2017年04月30日 05:43:11 +00:00Commented Apr 30, 2017 at 5:43
-
stackoverflow.com/questions/11064562/… check this stackoverflow question & answerKeshan Nageswaran– Keshan Nageswaran2017年04月30日 05:48:49 +00:00Commented Apr 30, 2017 at 5:48
-
Do you want to delete the html elements from DOM?Pankaj Shukla– Pankaj Shukla2017年04月30日 06:13:02 +00:00Commented Apr 30, 2017 at 6:13
3 Answers 3
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
3 Comments
Array.from is your friend... when you see it in code and don't have a clue what it's for gThis in fact is an HTMLCollection, which is "array-like". See https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection for more details.
Comments
getElementsByClassName return a HTMLCollection. It does not have splice method.
You can convert the HTMLCollection to array to use the splice method.
var tweetParentsArray = Array.prototype.slice.call(document.getElementsByClassName("js-stream-tweet"))
if (tweetParentsArray.length == 0) {
return;
}
tweetParentsArray.splice(0, index)