1

I have a list of select elements inside a forEach loop and want only the first element which is at index 0.

This element will have a different method, I'm trying to prevent a repetitive code i don't want to create another method just for this single element, I've tried to figure it out but it seems i'm not successful.

var listOfSelect = document.querySelectorAll('select');

listOfSelect.forEach(function(element) {
  element.addEventListener('focus', function () {
      element.style.backgroundColor = "white";
  });
  element.addEventListener('blur', function () {
      element.style.backgroundColor = "#F0F0E7";
  });

  element.addEventListener('change', function () { // I would want to get the first element here 
    // 
  });
});
user-9725874
  • 831
  • 9
  • 15
  • Possible duplicate of [Javascript forEach() through an array: how to get the previous and next item?](https://stackoverflow.com/questions/38696860/javascript-foreach-through-an-array-how-to-get-the-previous-and-next-item) – Prashant Pimpale Jul 27 '19 at 11:54
  • Possible duplicate of [Get loop counter/index using for…of syntax in JavaScript](https://stackoverflow.com/questions/10179815/get-loop-counter-index-using-for-of-syntax-in-javascript) – Prashant Pimpale Jul 27 '19 at 11:56

2 Answers2

3

You can access the index as second parameter of forEach method, such as below

var listOfSelect = document.querySelectorAll('select');

listOfSelect.forEach(function(element, index) {
 ...

  element.addEventListener('change', function () { 
    // I would want to get the first element here 
    if (index === 0) {
      console.log('hi')
    }
  });
});
Isaac
  • 12,042
  • 16
  • 52
  • 116
1

forEach has following syntax

nodeList.forEach(callback(currentValue [, index [, array]])[, thisArg]);

So you can use

var listOfSelect = document.querySelectorAll('select');

listOfSelect.forEach(function(element,index,array) {
  element.addEventListener('focus', function () {
      element.style.backgroundColor = "white";
  });
  element.addEventListener('blur', function () {
      element.style.backgroundColor = "#F0F0E7";
  });

  element.addEventListener('change', function () { 
      console.log(array[0])
  });
});
adiga
  • 34,372
  • 9
  • 61
  • 83
Code Maniac
  • 37,143
  • 5
  • 39
  • 60