Answering Google- Passing a Random Number to a Div id in Javascript

by Rob Larsen

Occasionally I see specific searches that bring people to my site and I wonder if people actually found the answers they were looking for in my code articles. Sometimes I think they probably did, but sometimes I’m not so sure. So… I figured why not answer some of the more interesting pleas directly? Lord knows if anyone will ever need to do such a thing again, but if they do I’ll be ready for them (and I get to problem solve in public :) )

Anyway, here’s one that I thought was interesting. The exact search was:

how to pass random no to div id in javascript

The first result points to this site, but I’m almost certain the article it points to won’t be of any help.

This function would be of great help

function random_div_id(obj) {
//obj is the div to be randomized
//get a random integer between 1 and 10000
     rand_id = parseInt(Math.random()*10000);
//concatenate the old id, a dash and the random number into a new random id
//if you wanted, you could just pass the rand_id and be done with it.
     obj.setAttribute("id",obj.id+"-"+rand_id);
}
 

Here’s an example:

Leave a Reply