Krisztian Toth
Krisztian Toth

Reputation: 63

Uncaught TypeError. indexOf is not a function error

I am a rookie and trying to create js script to hide and make visible sections on a webpage. The previous parts seem to be working fine. The last part of the snippet returns this error:

scripts.js:29 Uncaught TypeError: sections.indexOf is not a function
    at nextSection (scripts.js:29)
    at <anonymous>:1:1

Can anyone tell me what I am not getting here?

/*
============================================
array of all sections
============================================
*/
var sections=document.querySelectorAll("section");

/*
============================================
Function to find the section that is being displayed (the one that doesn't have "not1st" as a class.)
============================================
*/

function findSection(){
for (var i=0; i<sections.length; i++) {
    if (sections[i].className.includes("not1st")){
        continue;
    } else {
        return sections[i];
    }}}

/*
============================================
Function to load the next section
============================================
*/

function nextSection() {
   sections[sections.indexOf(findSection())+1];
}

Upvotes: 2

Views: 4738

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

querySelectorAll doesn't return an array, it returns a NodeList. NodeLists don't have an indexOf function.

You can convert it to an array using Array.from:

var sections = Array.from(document.querySelectorAll("section"));

...or for older browsers without Array.from, Array#slice:

var sections = Array.prototype.slice.call(document.querySelectorAll("section"));

For more information, see the "For Array-Like Objects" part of my other answer here.

Upvotes: 8

Related Questions