O. Barinov O. Barinov - 2 months ago 8
HTML Question

Define JavaScript array using ids from html

I want to create a function to randomly pick up an image defined in HTML code.

I decided create an array for this purpose and store all the used images in there, for the function randomly select an element of the array.

Is there any simple way to define the array or simply don't use the array at all?

<img id="pcimg1" class="pcpics" src="image.jpg"></img>
<img id="pcimg2" class="pcpics" src="image2.jpg"></img>
<img id="pcimg3" class="pcpics" src="image3.jpg"></img>


I know it is possible to be defined in HTML through identifier but I am wondering if it could be done using
.js
file only.

Something like this:

var images = new Array("pcimg1", "pcimg2", "pcimg3");


Does not seem to work. Defining array through
src
is not good idea for me as well as I have some styles used for all the images. Thanks for an every possible solution

Answer

You probably wanted to get the elements by classname instead, and then just randomly pick one

var images = document.querySelectorAll('.pcpics');
var random = images[Math.floor(Math.random() * images.length)];

var images = document.querySelectorAll('.pcpics');

var random = images[Math.floor(Math.random() * images.length)];

console.log(random.id)
<img id="pcimg1" class="pcpics" src="image.jpg"></img>
<img id="pcimg2" class="pcpics" src="image2.jpg"></img>
<img id="pcimg3" class="pcpics" src="image3.jpg"></img>

Comments