2

I have a set of elements on a page all with the same class but all have a different id. I am looking to select a random element and obtain its id so it can then be used in another function.

<div id="7469" class="element"> ... </div>
<div id="0184" class="element"> ... </div>
<div id="3986" class="element"> ... </div>
<div id="1295" class="element"> ... </div>
<div id="5704" class="element"> ... </div>
and so on...
Jon
  • 144
  • 1
  • 14
  • 2
    If you select using `$('.element')` you can then pick a random number from 0 to the `length` of the resulting object and select one specific element by index. – Rory McCrossan Jan 03 '17 at 14:22

2 Answers2

1

Generate index randomly and get element based on the index. Use Math.random and jQuery eq() methods for that.

var $ele = $('.element');

console.log($ele.eq(Math.floor(Math.random()*($ele.length - 1))).attr('id'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="7469" class="element">...</div>
<div id="0184" class="element">...</div>
<div id="3986" class="element">...</div>
<div id="1295" class="element">...</div>
<div id="5704" class="element">...</div>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

First gather all divs with element class.

var elements = $(".element");

And then

var randomelement = elements[Math.floor(Math.random() * elements.length)];
var randomid = $(elements[randomelement].attr("id"))
console.log(randomid)

See this SO question

Community
  • 1
  • 1
Manos Kounelakis
  • 2,848
  • 5
  • 31
  • 55