0

I am trying to apply an onclick function to an array of three elements, but setting the onclick property of the array does not work. Any ideas would be really helpful. Thanks!

Here is my code:

var btnArray = [
document.getElementById('buttonOne'),
document.getElementById('buttonTwo'),
document.getElementById('buttonThree'),
];
console.log(btnArray); 
btnArray.onclick = function revilImg() {
console.log('hey');
}

2 Answers 2

2

Arrays don't have an onclick property. You need to iterate over it first (I have chosen to use Array#forEach), and attach the handler to each DOM element individually using addEventListener:

var buttons = [
  'buttonOne',
  'buttonTwo',
  'buttonThree'
].map(document.getElementById, document)

console.log(buttons)

function revealImage () {
  console.log('hey')
}

buttons.forEach(function (e) {
  e.addEventListener('click', revealImage)
})
<button id="buttonOne">#1</button>
<button id="buttonTwo">#2</button>
<button id="buttonThree">#3</button>

Sign up to request clarification or add additional context in comments.

2 Comments

Where did you find, or knew, that when passing document.getElementById to the map function, it needs the document as thisArg?
@LGSon document is just an instance of Document, and it so happens that getElementById is defined on Document.prototype instead of as an own property of document. Try running document.hasOwnProperty('getElementById'), and you'll see it is false.
1

Add event listeners like this, where you loop through the array and add a handler to each object

var btnArray = [
  document.getElementById('buttonOne'),
  document.getElementById('buttonTwo'),
  document.getElementById('buttonThree'),
];

console.log(btnArray);

for (var i = 0; i < btnArray.length; i++){
  btnArray[i].addEventListener('click', function(){
    console.log('hey');
  })
}

If your buttons share a common class, i.e. mybuttons, you can use querySelecorAll()

var btnArray = document.querySelectorAll('.mybuttons');

console.log(btnArray);

for (var i = 0; i < btnArray.length; i++){
  btnArray[i].addEventListener('click', function(){
    console.log('hey');
  })
}

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.