How can one properly iterate through an HTML Collection in JavaScript?

I need help with creating a slider using JavaScript. The code I have written below calculates the widths of the slides, but it's throwing an error in the console. Can someone advise on how to properly loop through and assign 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>

Answer №1

The issue is related to accessing the position length

let i = 0; i <= slides.length
              ^

This condition will try to access a non-existent position, so you should change it to:

let i = 0; i < slides.length
             ^

By doing this, the access will be from 0 up to length - 1

Answer №2

Consider utilizing querySelectorAll over the getElementsBy* methods when working with HTMLCollections. querySelectorAll returns a static NodeList that is easier to iterate over directly, ensuring it won't change during iteration and offers greater flexibility.

document.querySelectorAll('.slide').forEach(slide => {
  // do stuff with each slide
  slide.style.width = `${slideWidth}%`;
});

Avoid using traditional for loops as they may not clearly express your code's intention. Opt for higher-order functions like .map, .reduce, .filter whenever possible. Check out: and https://gist.github.com/robotlolita/7643014

(using .forEach helps prevent off-by-one errors)

Note that some older browsers may not support NodeList.forEach - ensure proper polyfilling if you plan to use this method in your distribution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The npm outdated command seems to ignore the caret notation specified in the package.json file

When looking at a package.json file that contains the following: "devDependencies": { "grunt": "^0.4.5", "grunt-concurrent": "^1.0.0", "grunt-contrib-jshint": "^0.10.0", "grunt-contrib-watch": "^0.6.1", "grunt-dev-update": "^1.1.0", ...

Learn how to easily insert a marker on a map using leaflet js in vue 3 with just a simple click

Hey everyone! I need some help with a challenge I'm facing. I can't seem to get click coordinates to create a new Marker on my map. Check out the image here And another image here ...

Dividing a massive dataset into smaller chunks and applying the same code to each individual segment

Dealing with my data in smaller chunks and applying a fuzzy-wuzzy code multiple times has been a challenging task for me. I have to split the data file into sections, run the code on each section separately, and then combine the results into one file. Is t ...

JS: I'm struggling to understand the scope

I've been working on adapting CouchDB's JS API to function asynchronously, but I'm encountering an unresolved error: You can find my version of the JS API here on Pastebin. Whenever I execute (new CouchDB("dbname")).allDocs(function(result) ...

Updating all images in a JQuery thumbnail gallery

I've been experimenting with jQuery and fancy box to create a special effect on my website. I wanted to display a large image with thumbnails below it, where clicking on a thumbnail would update the main image (similar to the RACE Twelve image example ...

How to remove a loop-rendered component from the DOM in Vue

My website has an image upload form where users can select multiple images. Once the images are selected, they are previewed and users can provide meta info such as Category and Type for each image. This functionality is implemented in the upload.vue file ...

Ways to extract metadata from a given URL

Recently, I've delved into the world of JavaScript and I'm looking to extract metadata from a given URL. Whenever a URL is entered into an input field, I want to retrieve its meta data - a simple task in HTML using JavaScript. However, every time ...

Error message in Leaflet JS: Unable to access property 'addLayer' because it is undefined when trying to display drawnItems on the Map

My attempt to showcase a Leaflet Map with polygon-shaped surfaces encountered an issue. Sometimes, I face the error "cannot read property 'addLayer' of undefined," but when the page is refreshed, the map renders correctly. I am unsure where I wen ...

The API request is experiencing delays due to the large dataset of 250,000 records

Utilizing API calls to retrieve data for the frontend is essential, but with a database table containing 250,000 rows, efficiency becomes a concern. In my .NET Core application, I implement the following query: IQueryable<Message> query = context.Me ...

Wait for Axios Request Interceptor to complete before sending another ajax call

One feature I have added is a request interceptor for all axios calls. This interceptor checks the JWT token and automatically refreshes it if necessary. axios.interceptors.request.use((config) =>{ const currentState = store.getState(); // get upd ...

Rearranging div placement based on the width of the screen

I am currently working on building a responsive website and I need two divs to switch positions depending on the screen width, both on initial load and when resizing. Despite my efforts in researching and trying various options, I have not been successful ...

Retrieve data from a text file using ajax and then return the string to an HTML document

Just starting out with ajax, I have a text file containing number values For example, in ids.txt, 12345 maps to 54321 12345,54321 23456,65432 34567,76543 45678,87654 56789,98765 Here is the Html code snippet I am using <html><body> < ...

The issue with Jquery.Validate not functioning properly when trying to upload a file

I have integrated jQuery validation into my ASP.NET MVC project, and it is functioning correctly with textboxes. However, I am encountering an issue with file uploads. Below is the code snippet I am using: @model ffyazilim.Management.Model.Credential.Crea ...

Can you explain the distinction between "(.....);" and "{......}" within the context of React?

Encountering an error indicated in the image for the following code: handlechange(event) { this.setState (prevState => { return( checked : !prevState.checked );}); } Interestingly, changing the round brackets after "return" to curl ...

utilize the flex index.html layout

Upon reviewing the template, I noticed that there is code implemented to check if the client has the necessary version. This code performs certain actions based on whether or not the required version is available. Additionally, there seems to be an <obj ...

Scroll bar malfunction in Highcharts

I am struggling to get the scroll bar working so that all categories can be displayed. I have tried different approaches but haven't been able to figure out where I'm going wrong. See the code in action here: http://jsfiddle.net/manraj/7racxxu0/ ...

Display issue with React TypeScript select field

I am working with a useState hook that contains an array of strings representing currency symbols such as "USD", "EUR", etc. const [symbols, setSymbols] = useState<string[]>() My goal is to display these currency symbols in a select field. Currently ...

Choose a particular optgroup simultaneously using custom JavaScript

Check out this Fiddle for an example I am facing a situation where I have two different types of option groups with options. My challenge is to ensure validation between these two groups. How can I achieve this? Situation 1 If I select something from g ...

Speaking about the `this` Vue component in an event listener context

Consider this Vue component that is equipped with a global event listener: let myApp = new Vue({ data: { foo: 0; }, methods: { handle: function(event) { this.foo = 1; // 'this' pertains to the handler, not ...

Conceal a division on a webpage according to the URL of the specific

<script> function hideSearchField() { if (/menu/.test(window.location.href)) { document.getElementById('searchfield').style.display = 'none'; } } hideSearchField(); </script> I am trying to accomplish this using Jav ...