jQuery Get Random Element From a Selection Returned By $(selector)

前端 未结 3 2320

If $(\'.my-element\') matches multiple element, is there a quick way to get a random element out of these?

3条回答
  •  再見小時候
    2021-02-20 10:36

    var numElements = $('.my-element').length;
    var randomNum = Math.floor(Math.random()*numElements);
    //Select your random element
    $('.my-element:nth-child(' + randomNum + ')');
    

提交回复
热议问题