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 
    // 
  });
});
2

2 Answers 2

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')
    }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

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])
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.