Aesthetic Cookie Aesthetic Cookie - 1 year ago 43
Javascript Question

How do I convert numbers into letter form, ex. 3 to three, and then className = three?

I am making a dice roller. This code gives the sum of the dice rolled.

function getSumDiceValue(){
var dice = diceWindowWrapper.getElementsByClassName("dice");
var diceTotal = 0;
for(var i = 0; i < dice.length; i++){
diceTotal += Number(dice[i].getAttribute("data-diceValue"));

return diceTotal;

I want to set the class name of zero to the value of getSumDiceValue(), but in letters.

That is if I roll a 6 then the value of getSumDiceValue() is equal to 6, and then I want zero.className to equal six. That is:

zero.className = six;

Then I would need to "plug it in" to this code:

var zero = document.createElement("li");
zero.className = <here>;


I think I need to make an array of some kind. But I am new to javaScript and not sure how I would go about doing that. Please add code to your answer.

Answer Source

Check this function. It get a numeric value as parameter and returnes this number as text. (Numbers 1 to 6 for the dice):

var diceResult = 6;

var getNumberText = function(num) {
  //Create an object that maps the relation between numeric and literal values of numbers
  var numTxtSet = {    
    1: 'one',
    2: 'two',
    3: 'three',
    4: 'four',
    5: 'five',
    6: 'six'
  //Check if the given parameter is a number
  if (num && !isNaN(num)) {
    return numTxtSet[num];

//Call the function passing 'diceResult' as parameter and store it's value to a variable
var res = getNumberText(diceResult);