Usually, when you search for an element by its id, it is usually unique, otherwise the use of class
instead of id
becomes more logical, however, if it is necessary to select multiple elements, you can be done using document.querySelectorAll
, for example
function Ejemplo()
{
//Uso querySelectorAll para seleccionar los elementos con id uno, dos y tres.
var Elementos = document.querySelectorAll('#uno, #dos, #tres');
//uso forEach para recorrer el arreglo de elementos que obtuve arriba
Elementos.forEach(function(item){
//Cambio el color de cada uno a fin de ejemplo
item.style.backgroundColor = "red";
});
}
div{
width: 20px;
height: 20px;
float: left;
background-color: blueviolet;
margin: 10px;
}
button
{
clear: both;
display: block;
margin-left: 10px;
}
<div id="uno"></div>
<div id="dos"></div>
<div id="tres"></div>
<button onclick="Ejemplo()">¡Probar!</button>
Clarification: ignore the css of the snippet that is purely from the example
However, as I mentioned at the beginning of the answer, if there is no particular requirement that prevents you from doing so, the ideal would be to use class
, since applying the same behavior to several id
would be the same. same, right?
To do so, a snippet could be the following:
function Ejemplo()
{
//Selecciono todos los elementos con la class 'clase'
var Elementos = document.getElementsByClassName('clase');
//Recorro el array obtenido
[].forEach.call(Elementos, function (item) {
//Cambio el color del div por fines demostrativos.
item.style.backgroundColor = "red";
});
}
div{
width: 20px;
height: 20px;
float: left;
background-color: blueviolet;
margin: 10px;
}
button
{
clear: both;
display: block;
margin-left: 10px;
}
<div class="clase"></div>
<div class="clase"></div>
<div class="clase"></div>
<button onclick="Ejemplo()">Probar!</button>