Add multiple ids in getElementById [duplicate]

試著忘記壹切 提交于 2019-12-04 16:35:59

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!