zufällig ein Element wählen

Wie man mit jQuery zufällig ein Unterelement auswählen (selektieren) kann

JavaScript


jQuery.noConflict();

jQuery(document).ready(function($){
  $('a.selectrandom').click(function(e) {
    e.preventDefault();
    $("#ulList li.item").css("background", "#ffffff");
    var max = $('#ulList li.item').length;
    var randInt = Math.ceil(Math.random()* max); 
    $('#ulList li.item:nth-child('+randInt+')').css("background", "#eeeeee");
  });
});

HTML Code


<ul id="ulList">
<li class="item">LI-Element 1</li>
<li class="item">LI-Element 2</li>
<li class="item">LI-Element 3</li>
<li class="item">LI-Element 4</li>
<li class="item">LI-Element 5</li>
<li class="item">LI-Element 6</li>
<li class="item">LI-Element 7</li>
<li class="item">LI-Element 8</li>
<li class="item">LI-Element 9</li>
</ul>
<a href="#" class="selectrandom">zufall</a>

Demo

  • LI-Element 1
  • LI-Element 2
  • LI-Element 3
  • LI-Element 4
  • LI-Element 5
  • LI-Element 6
  • LI-Element 7
  • LI-Element 8
  • LI-Element 9
zufall