Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

Uncaught TypeError: s[s.length] is undefined

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Slider</title>
</head>
<body>
<div id="slide">
    <img src="0.jpg">
    <img src="1.jpg">
    <img src="2.jpg">
</div>
<script>
    setInterval(function(){
        slide()
    },2000);
    let index = 0;
    function slide(){
        var s = document.getElementById("slide").getElementsByTagName("img");
        ++index;
        if(index == s.length) index = 0;
        if(index == 0)
        {
            s[s.length].style.display ="none";
        }
        else
        {
            s[index-1].style.display ="none";
            s[index].style.display ="inline";
        }
    }
</script>
</body>
</html>

error

0 likes
3 replies
vincent15000's avatar

You are trying to get the length of some variable which is probably not countable.

var s = document.getElementById("slide").getElementsByTagName("img");
console.log(s);

What do you see in the console ?

Nakov's avatar
Nakov
Best Answer
Level 73

You will need to do length-1 as you are going out of bounds by trying to use s[3] which obviously does not exists.. use this:

if(index == 0)
{
    s[s.length - 1].style.display="none";
}
2 likes

Please or to participate in this conversation.