I am trying to make a slider, and while the code below to calculate the widths of the slides works, it throws an error in the console. What is the correct way to loop through and a width to these elements?
Javascript
var calcSlideWidth = function(divId){
let slDiv = document.getElementById(divId);
let slides = slDiv.getElementsByClassName('slide');
slDiv.style = "width:"+ 100*slides.length +"%";
slideWidth = 100/slides.length;
for (let i = 0; i <= slides.length; i++ ){
slides[i].style = " width:"+ slideWidth +"%";
console.log(i);
}
}
window.onload = function(){
calcSlideWidth("slider");
}
HTML
<div class="slider-container">
<ul id="slider">
<li class="slide"><span>Slide 1</span></li>
<li class="slide"><span>Slide 2</span></li>
<li class="slide"><span>Slide 3</span></li>
</ul>
</div>
The getElementsBy* methods return HTMLCollections, which can be difficult to work with. Consider using querySelectorAll instead, which returns a static NodeList - unlike an HTMLCollection, it can be iterated over directly, it won't change while it's being iterated over, and it's much more flexible.
document.querySelectorAll('.slide').forEach(slide => {
// do stuff with each slide
slide.style.width = `${slideWidth}%`;
});
for
loops fail to clearly signal the intention of your code, and as such should be avoided whenever possible (prefer higher-order functions, such as .map, .reduce, .filter, ...). See also: http://qr.ae/RNMEGA and https://gist.github.com/robotlolita/7643014
(you'll never have an off-by-one error through .forEach
)
Note that NodeList.forEach is a new-ish method that some older browsers don't support - if you use this method, make sure to polyfill properly before distribution.
The error for sure is the access at position length
let i = 0; i <= slides.length
^
That condition will access to a none existing position, so you need to use this:
let i = 0; i < slides.length
^
That way, the access will be from 0
until length - 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.