-1

I'm trying to randomize an array with DOM elements, like this:

var allTargets=$('#target1, #target2, #target3, #target4');
var randomTargets=null;
randomTargets = allTargets[Math.floor(Math.random() * allTargets.length)];
console.log(randomTargets);

In the console I can see the array is shuffled each time I refresh the page. But when I try to trigger a method with the randomTargets variable, the program crashes. Something like this:

randomTargets.hide();

But without the random variable, the program works:

var allTargets=$('#target1, #target2, #target3, #target4');
allTargets.hide();

What am I doing wrong?

1
  • 1
    In the console I can see the array is shuffled each time I refresh the page." No, nothing is shuffling that (which is a jQuery object, not an array). You are picking a random element from the (unshuffled) jQuery object. Commented Apr 15, 2017 at 12:31

2 Answers 2

1

Perhaps you meant this which will not shuffle but just hide a random element based on a random number from 0 to length of allTargets

var $allTargets = $('#target1, #target2, #target3, #target4');
var rnd = Math.floor(Math.random() * allTargets.length);
$allTargets.eq(rnd).hide();
Sign up to request clarification or add additional context in comments.

Comments

0

Accessing a jQuery object "like an array" gives you a native DOM element which has no hide() method.

From the docs at https://api.jquery.com/get/

Each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get at the list item instead:

console.log( $( "li" )[ 0 ] );

So in your case $(randomTargets).hide(); will work.

1 Comment

well, the program crashes still

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.