Rachel Irene Lunan
Rachel Irene Lunan

Reputation: 3

Is it possible to convert a string into a node?

I'm trying to create a random name generator from a set list of names (from 1-10). I have assigned an id to each name (from "s01" to "s10") and am trying to write some JavaScript to randomly choose one from the list. This is what I have so far:

if (action === 'who') {
    console.log("who");
    let num = Math.floor((Math.random() * 10) + 1);
    console.log(num);
    if (num === 10) {
        numb = s10.textContent;
    } else {
        num = ("s0"+num);
        console.log(num);
        numb = num.textContent;
    }
console.log(numb);

But I'm getting console.logs as "undefined," unless the number generated was 10, and then it is fine.

I am trying to convert what comes up as num into the id but I'm not sure how to do it.

Upvotes: 0

Views: 63

Answers (1)

Barmar
Barmar

Reputation: 781098

When you write

num = ("s0" + num);

you're just creating a string, it doesn't try to use that as the name of a variable. So it doesn't access the node in the variable s06.

Use document.getElementById() to get the element with a specific ID, rather than trying to access it as a variable. You can use string concatenation to create the argument.

var id = num < 10 ? "s0" + num : "s" + num;
var element = document.getElementById(id);
var numb = element.textContent;

Upvotes: 1

Related Questions