Picking up random elements from DOM using jQuery

tumblr_n1zv0cTukw1tubinno1_1280

Selecting a group of DOM elements is super duper easy these days using CSS selectors, or a particular element via their ID. But what about picking up a random element from these group of elements? In this article I am going to show you how to do it by extending jQuery

Let’s consider that we have the following markup. Now we will pick a random button and change it’s value

[sourcecode language=”html”]
<div class="container">
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
</div>
[/sourcecode]

Let’s extend jQuery and add a random() function to it

[sourcecode language=”javascript”]
$.fn.random = function() {
return this.eq(Math.floor(Math.random() * this.length));
}
[/sourcecode]

Now we can pick up a random button and change it’s value quite easily.

[sourcecode language=”javascript”]
$(".container button").random().html("Click Me");
[/sourcecode]

That was easy, eh? Hope you’ll like it.