I am trying to run the following code but I KEEP GETTING THE ERROR. I also tried adding document.addEventListener(‘DOMContentLoaded’, (event) => but it is still not working. It dosn’t give me error if I put the code inside console. It also doesn’t give me error when I load it for the first time. But as soon as I refresh it starts giving me errors.
import './Slider.css';
import Acc from './Accomodation/Acc'
import Flora from './Flora/Flora'
import Food from './OurFood/Food.js'
import Trek from './Treks/Treks';
import View from './OurView/View';
import Indoor from './IndoorGames/games';
let slideIndex = 0;
SlideShow()
function SlideShow(){
let slides = document.getElementsByClassName("slide")
console.log(slides)
for (let i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
console.log(slideIndex)
console.log(slides)
if (slideIndex === 0) {slideIndex = 1}
else if (slideIndex === slides.length) {slideIndex = 1}
else if (slideIndex > slides.length) {slideIndex = 1}
console.log(slides[slideIndex])
slides[slideIndex-1].style.display = "block";
setTimeout(SlideShow, 10000);
}
function Slider() {
return (
<div className='Slider'>
<h1>Experiences</h1>
<hr />
<div className='MySlides'>
<div className='1 slide fade'>
<Acc></Acc>
</div>
<div className='2 slide fade'>
<Flora></Flora>
</div>
<div className='3 slide fade'>
<Food></Food>
</div>
<div className='4 slide fade'>
<Trek></Trek>
</div>
<div className='5 slide fade'>
<View></View>
</div>
<div className='6 slide fade'>
<Indoor></Indoor>
</div>
</div>
</div>
)
}
export default Slider;
2
Answers
You can use
It will log the error
And the main problem is
slides[slideIndex-1]
does not have values so that it can not readstyles
propertyError message:
According to the error message, your code is trying to call the
style
property; but a specific object doesn’t have thestyle
property. What do I mean by a specific object? An example:So, we need to look at the references of
style
in your code, and locate the specific parent objects in your code:slides[i].style.display = "none";
-> the parent object isslides[i]
slides[slideIndex-1].style.display = "block";
-> the parent object isslides[slideIndex-1]
So,
slides[i]
orslides[slideIndex-1]
objects don’t have thestyle
property.