2

all.

I am trying to create an array where I can change the color of the fonts within them.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Array Font Colors</title>
</head>

<body>
<script type="application/javascript">
    var colors= new Array("Black", "White", "Yellow");

    for(var a=0; a<colors.length; a++){
        document.write(colors[a]+ "<br>");
        }

</script>   
</body>
</html>

The above is what I have that makes the array, and displays it. I am not sure how to change the color of each element however to its given array value. For example, since the second array element value is White, make the font color white. I am new to JavaScript and am a bit confused on how this is done.

Thank you

4 Answers 4

1

Apply css to document.write

<html>
    <head>
        <meta charset="utf-8">
        <title>Array Font Colors</title>
    </head>

    <body>
        <script type="application/javascript">
            var colors= new Array("Black", "White", "Yellow");

            for(var a=0; a<colors.length; a++){
            document.write("<p style='color:"+colors[a]+"'>"+colors[a]+ "</p>");
            }

        </script>   
    </body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of using document.write, append a span tag to the body.

Replace that document.write statement by

document.body.innerHTML += "<span style='color:" + colors[a] + "'>" + colors[a] + "</span>";

Comments

0

not the best way but try this
document.write(colors[a].fontcolor("yourcolor")+ "<br>")

can be any css color // #db3f3f ,"red" etc..

Comments

0

You can try that in both ways by using document.body.innerHTML or document.write

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Array Font Colors</title>
</head>

<body>
<script type="application/javascript">
    var colors= new Array("Black", "White", "Yellow");

    for(var a=0; a<colors.length; a++){
     //  document.body.innerHTML += "<div style='color:" + colors[a] + "'>" + colors[a] + "</div>";
       //or
        document.write("<div style='color:" + colors[a] + "'>" + colors[a] + "</div>");
        }
       

</script>   
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.