2

How to use this script with multiple ids? Does not work on the second id that I try to add

<script type="text/javascript">
window.onload = (function () {
var elem = document.getElementById("id1","id2").onclick = function()
{
fbq('track', 'InitiateCheckout');
}
});
</script>
Vivek
  • 11,938
  • 19
  • 92
  • 127
Sam Provides
  • 269
  • 2
  • 6
  • 17

3 Answers3

11

You can use querySelectorAll to select many items by their IDs:

var items = document.querySelectorAll('#id2, #id3, #id5');

for (var i = 0; i < items.length; i++)
{
  items[i].onclick = function() { 
    this.innerText = this.innerText + '!';
  };
}
2, 3, 5 are working:

<p id="id1">I am 1</p><p id="id2">I am 2</p><p id="id3">I am 3</p><p id="id4">I am 4</p><p id="id5">I am 5</p>

However, creating a common class sounds much better.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
4

getElementById only takes one ID, but you can do this to select more than one element:

document.querySelectorAll('#id1, #id2');

...but you should not use that to create an event listener for every element. Better create one event listener for the whole document instead, for example:

document.addEventListener('click', handleClickEvents, false);

function handleClickEvents(evt) {
    myEventTarget = event.target;

    if (myEventTarget.id === 'id1') {

    } else if (myEventTarget.id === 'id2) {

    }
}

...or even better, use a framework like React or Angular.

andyrandy
  • 72,880
  • 8
  • 113
  • 130
1

The getElementById takes only one parameter, the id of the element you want to select. You can't pass to id more than one ids.

For more documentantion on this, please have a look here.

If you want to select multiple elements and attach to them the same event handler, you can use another approach.

First you have to add the same class to each of them, for instance js-classname.

Then you can select them using the method getElementsByClassName. This method will return to you an array like object containing all the elements with the class you specified.

If you need more information about this, please have a look here.

Christos
  • 53,228
  • 8
  • 76
  • 108