0

FIXED! I CHANGED "#slide" to ".slide", that was the problem. Thanks everyone!

Hello, people of Stack Overflow. I have encountered a problem with my code, and it doesn't seem to be hiding the elements when it should be.
Javascript:

let sliderImages = document.querySelectorAll('#slide'),
     arrowRight = document.querySelector(".next"),
     arrowLeft = document.querySelector(".prev"),
     current = 0;
//            reset all images
function reset(){
    for(let i = 0; i < sliderImages.length; i++){ 
        // "let" means make a variable which will only be used in the LOCAL scope.
        sliderImages[i].style.display = "none";
    }
}
function startSlide(){
    reset();
}
startSlide();
function test(){
    console.log("hello!") // to prove that this file is running
}
test();

The result I'm expecting is for all the images/things with div "#slide" to be invisible. Instead, I get no change on the webpage. If posting the HTML would help, I will. I have checked, and I believe there to be no typos in the names.

7
  • 6
    id is supposed to be uniques on a page. Can you also post the corresponding HTML and also how you are including the script ? Commented Dec 8, 2017 at 0:24
  • Any errors in your console? Where in the document is your <script> tag, in the <head> or <body>? If <body>, where exactly? Commented Dec 8, 2017 at 0:25
  • 1
    instead of querySelectorAll use getElementById and be sure you are using #slide once in your DOM Commented Dec 8, 2017 at 0:32
  • @ColinCline Why would OP use getElementById when they want multiple elements? (hence the for loop) The OP needs to use a class.... Commented Dec 8, 2017 at 0:46
  • @epascarello Is OP said he need multiple slider in one page? Commented Dec 8, 2017 at 0:59

1 Answer 1

2

Element IDs must be unique on the page. You seem to have more than one #slide, so my suggestion is to change from ID to class, so your divs will be:

<div class="slide">...</div>

This way, you can select them by simply using:

let sliderImages = document.querySelectorAll('.slide');

Then iterating over them with:

sliderImages.forEach(function(sliImg) {
  sliImg.style.display = "none";
});
Sign up to request clarification or add additional context in comments.

1 Comment

FYI, NodeList.prototype.forEach has limited browser support at this time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.