I go through the collection of elements with a forEach or FOR loop and for some reason only outputs the attribute value of the first element and the rest null, although the elements themselves output normally

var sliders = document.querySelectorAll('.slide'); var count = 0; console.log(count); document.querySelector('.next').onclick = function() { count++; sliders.forEach(function(i) { console.log(i.getAttribute('num')); }); }; 
 <div class="next">Click me</div> <div class="slide" num="0"></div> <div class="slide" num="1"></div> <div class="slide" num="2"></div> 

Closed due to the fact that off-topic participants Grundy , LFC , 0xdb , aleksandr barakin , Enikeyschik February 19 at 8:21 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • "The question is caused by a problem that is no longer reproduced or typed . Although similar questions may be relevant on this site, solving this question is unlikely to help future visitors. You can usually avoid similar questions by writing and researching a minimum program to reproduce the problem before publishing the question. " - Grundy, LFC, 0xdb, aleksandr barakin, Enikeyschik
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • He did not go through a cycle, because he did not perform this task. - Ruslan Semenov
  • I think you do not quite understand what a cycle is ... For this task it is better to use if(){} - Air
  • And the count is not from this play at all - Air
  • possibly. I’m trying to write my own slider myself, but I’m blunt, I’m supposed to make a display with the next one on the current slide when I click on it. Well, definitely I am doing something wrong as the first time =) - Teapot
  • one
    In the snippet, everything is displayed. What needs to be done to reproduce the problem? - Grundy

2 answers 2

Here is a good example, read the comments.

 var gnext = document.getElementById('nextPicture'); var gprev = document.getElementById("prevPicture"); var elem = document.getElementsByTagName('li'); // первому элементу сразу задаем класс, чтобы он был виден elem[0].classList.add('visible'); let count = null; function _count(direction) { // direction - это аргумент который определяет // направления // если нажимается кнопка следующий next if (direction === '_next') { // и count равен длине массива elem-li (- 1) if (count == elem.length - 1) // count обнуляем count = 0; else // если count не равен длине массива elem-li (- 1) count++; // а тут проверяем обратное действие } else if (direction === '_prev') { if (count == 0) count = elem.length - 1; else count--; } // А вот тут уже цикл for (let i = 0; i < elem.length; i++) { // Чтобы у всех elem удалить класс visible elem[i].classList.remove('visible'); } // А тут добавляем класс visible elem с нужным индексом elem[count].classList.add('visible'); } // ну а тут запускаем _count(direction) gnext.addEventListener('click', function() { // задавая направления _count('_next'); }) gprev.addEventListener('click', function() { _count('_prev'); }) 
 ul { position: relative; } li { opacity: 0; position: absolute; } .visible { opacity: 1; } 
 <div class="slider"> <button id="prevPicture">Prev</button> <button id="nextPicture"> Next</button> <ul> <li><img src="http://via.placeholder.com/250x250/33ff99/555555?text=Slid1"></li> <li><img src="http://via.placeholder.com/250x250/33ff99/555555?text=Slid2"></li> <li><img src="http://via.placeholder.com/250x250/33ff99/555555?text=Slid3"></li> <li><img src="http://via.placeholder.com/250x250/33ff99/555555?text=Slid4"></li> <li><img src="http://via.placeholder.com/250x250/33ff99/555555?text=Slid5"></li> <li><img src="http://via.placeholder.com/250x250/33ff99/555555?text=Slid6"></li> </ul> </div> 

  • I thank for the help, this is what you need, everything is easier for the dem I thought up =) - Kettle

That's corrected, but why cout you?

 var sliders = document.querySelectorAll('.slide'); var count = 0; function fn_count() { count++; sliders.forEach(function(i) { console.log(i.getAttribute('num')); }); }; 
 .next { cursor: pointer; text-align: center; border: 1px solid black; padding: 1em; } 
 <div class="next" onclick="fn_count()">click</div> <div class="slide" num="0"></div> <div class="slide" num="1"></div> <div class="slide" num="2"></div> 

  • thanks It works. count is needed to compare the attribute and select the next one by number - Kettle
  • What is the difference between this code and the code in question? Given that the behavior is exactly the same - Grundy
  • The code in the header was corrected after the question. - Ruslan Semenov