简体   繁体   中英

Selecting a random HTML element using JavaScript only

I'm trying to select an element from my HTML code, to then use it in JavaScript (it needs to be highlighted). The HTML consists of a table with 36 td's.

My code so far:

var box;
function getRandom()
{
    return (Math.floor(Math.random()*37))
}
function highlight()
{
    box = document.getElementById(getRandom());
    box.style.backgroundColor = "yellow";
}

If anyone can give me any pointers, it'd be appreciated. I know it would be easy using jQuery, but I haven't begun learning that yet. Edit: excerpt of the HTML code, this goes up to name="36".

<table id="reflexTable">
    <tbody>
    <tr>
      <td name="1"></td>
      <td name="2"></td>
      <td name="3"></td>
      <td name="4"></td>
      <td name="5"></td>
      <td name="6"></td>
    </tr>

getElementById gets the element which has the matching id . Your table data cells don't have an id at all. They have a name, but HTML doesn't allow that.

Switch to id.

HTML 4 doesn't allow an id to start with a number. Prefix the id with a common string. Then:

document.getElementById("foo" + getRandom());

A nicer way that does not involve setting element ids:

function highlight() {

    // get all TDs that are descendants of table#reflexTable:
    var tds = document.getElementById('reflexTable').getElementsByTagName('td');

    // get a random int between 0 (inclusive) and tds.length (exclusive)
    var rand = Math.floor( Math.random() * tds.length );

    // highlight td at that index
    tds[rand].style.backgroundColor = "yellow";

}

The big advantage of this method is that you can add/remove as many TDs as you please without needing to edit your JS to generate a valid random number.

You're not setting the id attribute, you're setting the name attribute, change it to:

<td id="1"></td>

...etc

Several things:

  1. You should declare the box variable inside the highlight function.

  2. You have to convert that random number to a string.

  3. Quentin mentioned something important--you should give each table element an id of something like "s0","s1","s2", etc...

  4. Start the naming at 0 because your getRandom function will sometimes return it.

function highlight(){ var number; number = getRandom().toString(); var box; box = document.getElementById("s" + number); box.style.backgroundColor = "yellow"; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM