how to call several ids in a javascript code

0

I want to call several ids in the javascript code so I do not have to create a different code for each Show more:

button
<p><a href="javascript:mostrar();">Mostrar</a></p><div id="flotante"style="display:none;"><div id="close"><a href="javascript:cerrar();">cerrar</a></div> --CONTENIDO--</div>

I've already tried but it does not work, I've also tried with ByClassName but neither, does anyone know how I do it? Javascript code

function mostrar() {
        div = document.getElementById('flotante');
        div.style.display = '';
    }

    function cerrar() {
        div = document.getElementById('flotante');
        div.style.display = 'none';
    }
    
asked by code2018 10.10.2018 в 03:31
source

2 answers

3

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>
    
answered by 10.10.2018 в 03:47
2

It's true, getElementById only returns 1 value. If you add class="floating" to your divs, you could get the list with one of the options:

 getElementsByClassName("flotante")
 querySelectorAll("div.flotante") 
    
answered by 10.10.2018 в 05:13