Blanket431
Blanket431

Reputation: 572

Add class to random li in all ul's

<div id="question-1" name="question" 
    <ul>  
        <li name="347815" class="MULTIPLE" id="7548094" value="7548094">1</li>
        <li name="347815" class="MULTIPLE" id="7548095" value="7548095">2</li>
        <li name="347815" class="MULTIPLE" id="7548096" value="7548096">3</li>
        <li name="347815" class="MULTIPLE" id="7548097" value="7548097">4</li>
    </ul>
</div>

<div id="question-2" name="question" 
    <ul> 
        <li name="347818" class="MULTIPLE" id="7548140" value="7548140">1</li>
        <li name="347818" class="MULTIPLE" id="7548143" value="7548143">2</li>
        <li name="347818" class="MULTIPLE" id="7548168" value="7548168">Hemköp</li>
        <li name="347818" class="MULTIPLE" id="7548169" value="7548169">3</li>
        <li name="347818" class="MULTIPLE" id="7548184" value="7548184">4</li>
        <li name="347818" class="MULTIPLE" id="7548195" value="7548195">5</li>
        <li name="347818" class="MULTIPLE" id="7548208" value="7548208">6</li>
    </ul>
</div>

I need a js "jquery" code to select a random li element from all ul lists. The list number changes constantly so I need to use something like .find();

This is the code that I have right no but it doesn't select one li in all ul, it selects random li in random ul:

var list = $('ul > li');
list.eq(parseInt(Math.random()*list.length)).addClass('selected');

Thank you guys :)

UPDATE:

@MTCoster has the right answer, here is it:

$("ul").each(function() { var liArr = $(this).children("li"); $(liArr[Math.floor(Math.random() * liArr.length)]).addClass('selected'); });

Upvotes: 1

Views: 1352

Answers (2)

MTCoster
MTCoster

Reputation: 6145

The code you have at the moment is creating a single array of all li elements that exist within a ul element, then selecting one of them. What you need to do is select all the ul elements first, then select a random li element from each one. Try something like this:

$("ul").each(function() {
  var liArr = $(this).children("li");
  $(liArr[Math.floor(Math.random() * liArr.length)]).addClass('selected');
});

Edit: you have to wrap the selected element from the array in a jQuery selector; I've updated the code to reflect this.

Upvotes: 2

guest271314
guest271314

Reputation: 1

Try using .each()

   // select all `ul` elements
   $("ul").each(function() {
      // select all `li` elements that are children of `this` `ul`
      var list = $("> li", this);
      list.eq(Math.random() * list.length).addClass("selected");
   })

Upvotes: 3

Related Questions