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

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:

2 thoughts on “Answering Google- Passing a Random Number to a Div id in Javascript

  1. Is there a way to style that specific div with CSS, even though it changes the div id upon each load?
    for example something like:
    #Sample-999 { height: 21px; }
    #Sample-999:hover { height: 300px !important; }
    so that in this scenario when you hover over that div the height will change. and still be functional if the div id changes numbers

Leave a Reply

Your email address will not be published. Required fields are marked *