0

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

3
  • check this up. Commented Sep 18, 2016 at 15:25
  • You can use document.getElementsByClassName, for example, to get array of references to all pic elements in your document. Then process it as you wish. Commented Sep 18, 2016 at 15:26
  • as answered by @adeneo you can use class names.... Commented Sep 18, 2016 at 15:28

1 Answer 1

6

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help, it helped indeed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.