-1

i have for example 15 div tags with a certain class name in a page

<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>

and i can select them using jquery

var targetDivs = $(' .className ');

it is going to return 15 div tags in this case but i want to randomly pick only 9 of them and store them in another variable

k961
  • 577
  • 1
  • 5
  • 19
  • 4
    you could store the result of `$(' .className ');` in an array and randomly select elements from there – empiric Nov 17 '16 at 19:54
  • 1
    Possible duplicate of [jQuery select random elements with same class](http://stackoverflow.com/questions/11186631/jquery-select-random-elements-with-same-class) or [Select 2 random divs with the same class jQuery](http://stackoverflow.com/q/28292024/4202224) – empiric Nov 17 '16 at 19:54
  • @empiric 15 div tags would be in array ?? – Mahi Nov 17 '16 at 19:55
  • @Mahi yes, why should that be a problem? – empiric Nov 17 '16 at 19:55
  • @empiric i am asking `$(' .className ')` will return array of object or object containing array ?? or jquery object – Mahi Nov 17 '16 at 19:57
  • Does it have to be 9, or just a random number of them? – Nick G Nov 17 '16 at 19:57
  • @Mahi oh ok I see, it is an array containing objects. Therefore e.g. `$(' .className ')[0]` will work – empiric Nov 17 '16 at 20:00
  • @empiric `$("li") instanceof Array ` is showing false – Mahi Nov 17 '16 at 20:02
  • @Mahi ok let me rephrase that: It's an array-like object (I think that's the official term here). So it can be accessed either as an object or an array – empiric Nov 17 '16 at 20:04
  • 1
    @empiric "Array-like" objects do not implement the full interface of `Array.prototype` and you should be very careful not to treat them like real arrays. They will have a `length` property and can be iterated and they may even support *some* of the `Array.prototype` members, but they won't support all of them. – Scott Marcus Nov 17 '16 at 20:06
  • @ScottMarcus thank you . so `$("li") is same as nodeLists in plain javascript ?? – Mahi Nov 17 '16 at 20:07
  • @Mahi No, it's not. The results of a JQuery query returns a JQuery object, known as "wrapped set" and is also an array-like object, but it is not a node list. – Scott Marcus Nov 17 '16 at 20:10
  • @ScottMarcus thank you . i understand and now you will see my answer on every question :P – Mahi Nov 17 '16 at 20:19

4 Answers4

2

You just need to generate a random number and then use that number as the basis for looping:

var targetDivs = document.querySelectorAll('.className');

var randomAmount = prompt("What is the upper limit for a random number you want?");

var randomNum = Math.floor(Math.random() * randomAmount);
console.log("Random number is: "  + randomNum);

for(var i = 0; i < randomNum; ++i){
   var randomNode = Math.floor(Math.random() * targetDivs.length);
   console.log("Result includes: " + targetDivs[randomNode].textContent);
}
<div class="className">CONTENT 1</div>
<div class="className">CONTENT 2</div>
<div class="className">CONTENT 3</div>
<div class="className">CONTENT 4</div>
<div class="className">CONTENT 5</div>
<div class="className">CONTENT 6</div>
<div class="className">CONTENT 7</div>
<div class="className">CONTENT 8</div>
<div class="className">CONTENT 9</div>
<div class="className">CONTENT 10</div>
<div class="className">CONTENT 11</div>
<div class="className">CONTENT 12</div>
<div class="className">CONTENT 13</div>
<div class="className">CONTENT 14</div>
<div class="className">CONTENT 15</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
2

One approach I'd suggest is the use of a simple plugin:

(function($) {

  // naming the new plugin ('getRandom'):
  $.fn.getRandom = function(n) {

    // creating an Array by passing the jQuery collection
    // the 'this' passed to the function to the get()
    // method, which takes the passed-in collection
    // and returns a jQuery Array:
    var collection = this.get(),

      // creating an Array, using an Array-literal:
      result = [],

      // initialising a variable for use, later:
      rand;

    // converting the passed-in argument, 'n', into a
    // base-10 ('10') Number, using parseInt() (this
    // does no harm if 'n' is already a Number, but
    // ensures that, if a String is passed in ('3' for
    // example) we get a Number back out:
    n = parseInt(n, 10);

    // while n is still truthy (so non-zero):
    while (n) {

      // we generate a random number in the range of
      // 0 to the length of the collection Array:
      rand = Math.floor(Math.random() * collection.length);

      // we use the random number as an index, and
      // push the Array-element at that index in the
      // collection Array into the result Array:
      result.push(collection[rand]);

      // we then remove the element at that index from the
      // collection Array, passing in the same index ('rand')
      // and deleting one element ('1'):
      collection.splice(rand, 1);

      // decrement the n variable:
      n--;
    }

    // convert the result Array of elements back into
    // object, and return that object to the calling
    // context for chaining:
    return $(result);
  }
})(jQuery);

(function($) {
  $.fn.getRandom = function(n) {
    var collection = this.get(),
      result = [],
      rand;

    n = parseInt(n, 10);

    while (n) {
      rand = Math.floor(Math.random() * collection.length);
      result.push(collection[rand]);
      collection.splice(rand, 1);

      n--;
    }

    return $(result);
  }
})(jQuery);

$('.className').getRandom(10).css({
  'opacity': '0.2'
})
.className {
  display: inline-block;
  width: 3em;
  height: 3em;
  box-sizing: border-box;
  border: 2px solid #000;
  text-align: center;
  overflow: hidden;
  counter-increment: boxCounter;
  position: relative;
}
.className::after {
  content: counter(boxCounter, decimal-leading-zero);
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>

JS Fiddle demo.

As most of the jQuery plugin above is written in plain JavaScript this is, of course, similarly easily-possible in plain JavaScript, albeit as a function, rather than a method or prototype-extension (although, if you wish to do it that way, it remains easily-possible to do so, albeit not necessarily advised):

function getRandomFrom(haystack, n) {

  // ensuring that we have an Array, assuming we're
  // passed an Array-like Object (such as a NodeList,
  // HTMLCollection or, even, an Array):
  haystack = Array.from(haystack);

  // ensuring that the variable n is a Number, using
  // parseInt():
  n = parseInt(n, 10);

  // creating an empty Array:
  var result = [],

      // initialising a variable for later use:
      rand;

  // while n is truthy (non-zero):
  while (n) {

    // we generate a random number between 0 and
    // the Array-length:
    rand = Math.floor(Math.random() * haystack.length);

    // we use the random number as an index for the Array,
    // and push the Array-element held at that index to the
    // result Array:
    result.push(haystack[rand]);

    // we remove that Array-element from the Array, using
    // Array.prototype.splice():
    haystack.splice(rand, 1);

    // decrement n, to ensure we don't have an infinite
    // while loop:
    n--;
  }

  // return the result Array to the calling context:
  return result;
}

function getRandomFrom(haystack, n) {
  haystack = Array.from(haystack);
  n = parseInt(n, 10);

  var result = [],
    rand;

  while (n) {
    rand = Math.floor(Math.random() * haystack.length);
    result.push(haystack[rand]);
    haystack.splice(rand, 1);
    n--;
  }
  return result;
}

var elems = document.querySelectorAll('.className');

getRandomFrom(elems, 5).forEach(el => el.classList.add('selected'));
.className {
  display: inline-block;
  width: 3em;
  height: 3em;
  box-sizing: border-box;
  border: 2px solid #000;
  text-align: center;
  overflow: hidden;
  counter-increment: boxCounter;
  position: relative;
}
.className::after {
  content: counter(boxCounter, decimal-leading-zero);
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: #fff;
}
.className.selected {
  opacity: 0.25;
  border-color: red;
}
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>
<div class="className">CONTENT</div>

References:

Bibliography:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
2

You could use Jquery Each and build a unique and random element array.
You could then loop out on your element array to place the elements where you want this randomization to occur.

var divs = [];
var indexs = []; 

while(indexs.length < 9){
   var num = Math.floor(Math.random() * 9) + 1;
  indexs.push(num);
  indexs = $.unique(indexs);
}

$('.className').each(function(index, element){

    if(indexs[index]){
        divs.push($('.className').eq(indexs[index]));
    }
});
console.log(divs);
David Muir
  • 34
  • 1
  • 5
1

Example below using ES6 Map:

let results = new Map();
for(let i = 0; i < 9; i++) {
    let index= null;
    while(index=== null || results.has(index)) {
        index= Math.floor(Math.random() * 9);
    }
    results.set(index, document.querySelectorAll('.className')[index]);
}
for (let result of results.values()) {
     console.log(result.textContent)
} 
<div class="className">CONTENT 1</div>
<div class="className">CONTENT 2</div>
<div class="className">CONTENT 3</div>
<div class="className">CONTENT 4</div>
<div class="className">CONTENT 5</div>
<div class="className">CONTENT 6</div>
<div class="className">CONTENT 7</div>
<div class="className">CONTENT 8</div>
<div class="className">CONTENT 9</div>
<div class="className">CONTENT 10</div>
<div class="className">CONTENT 11</div>
<div class="className">CONTENT 12</div>
<div class="className">CONTENT 13</div>
<div class="className">CONTENT 14</div>
<div class="className">CONTENT 15</div>
Paul Grimshaw
  • 19,894
  • 6
  • 40
  • 59