Manuel Pavone
Manuel Pavone

Reputation: 3

Weird behavior in GetElementsByClassName

I've tried to get an array of pictures to create an simple carousel. When I try to change the classname to show or hide some elements my array is modified I don't know why...

This is my fiddle https://jsfiddle.net/op1nzkxc/

HTML :

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style/style.css">
</head>
<body>
<div id="my-carousel">
    <div>
        <div class="car-hide">Picture 1</div>
        <div class="car-hide">Picture 2</div>
        <div class="car-hide">Picture 3</div>
    </div>
</div>
<script src="js/script.js"></script>
</body>
</html>

Javascript :

pictures = [];

function getAllElementsHidden(){
    return document.getElementsByClassName("car-hide");
}

function startSlide(){
    pictures = getAllElementsHidden();
    console.log(pictures);
    pictures[1].className = "car-show";
    console.log(pictures);
}

startSlide();

CSS :

body{
    text-align: center;
}

ul{
    text-decoration: none;
}

.car-hide{
    display: none;
}

Can someone help me please?

Upvotes: 0

Views: 60

Answers (1)

Amadan
Amadan

Reputation: 198324

.getElementsByClassName returns a live collection of elements. It is always up to date. If you remove a feature that made it qualify, then it is no longer present. If you need to keep an invariant collection of nodes for later, you need to duplicate it using .slice; however, since the live collection is not an Array but an array-like object, we need to take Array's .slice and apply it on the live collection:

var pictures = Array.prototype.slice.call(getAllElementsHided())

Upvotes: 3

Related Questions