A getElementById can be used if it exists several times but with a differentiator?

2

I want to know if it is possible to use the Id of an element if it is used

For example we have

<img id="image1" onclick="usarImagen();" class="img-responsive center-block" src="images\imagen1.jpg" alt="banner1" align="middle"/>
<img id="image2" onclick="usarImagen();" class="img-responsive center-block" src="images\imagen2.jpg" alt="banner2" align="middle"/>
<img id="image3" onclick="usarImagen();" class="img-responsive center-block" src="images\imagen3.jpg" alt="banner3" align="middle"/>

and that can be called like this:

...

function usarImagen() {
        var image = document.getElementById("image*").value;
...

instead of specifying one by one and taking only the one that is used

    
asked by CarlosOro 20.05.2016 в 00:37
source

2 answers

2

Use the document.querySelectorAll() method to get an array with all the elements that match the specified selector:

var imagenes = document.querySelectorAll("[id*='image' i]");
console.log(imagenes.length); // 3 images 

The selector is [id*='image'] where id*= looks for a partial concidence of the string image , it can be at the beginning, in the middle or at the end.

    
answered by 20.05.2016 / 00:46
source
0

The easiest way to do it is using jQuery:

$(function(){
  var images = $('img[id^="image"]');
  var resultado = '';
  images.each(function(i) { resultado += 'Imagen ' + images[i].id + '\n'; });
  $('#resultado').text(resultado);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="image1" onclick="usarImagen();" class="img-responsive center-block" src="images\imagen1.jpg" alt="banner1" align="middle"/>
<img id="image2" onclick="usarImagen();" class="img-responsive center-block" src="images\imagen2.jpg" alt="banner2" align="middle"/>
<img id="image3" onclick="usarImagen();" class="img-responsive center-block" src="images\imagen3.jpg" alt="banner3" align="middle"/>

<p>&nbsp;</p>

<pre id="resultado"></pre>
    
answered by 20.05.2016 в 00:49