0

I would like to add different colours to different texts. The list of colours that I would like to add is stored in an array. How will I use that array to assign colours to my texts? Please check the code that I have written. The text "hai" is supposed to be in cyan colour. But the output is not as expected.

<!doctype html>
<html>
<body>
  <script>
    var colors=['blue','cyan','gold','grey','green'];
  </script>
  <h1 style="color:colors[1]">hai</h1>
</body>
</html>

2 Answers 2

2

You should first give your desired element an id then retrieve it through js and style it:

<!doctype html>
<html>
  <body>
    <script>
      window.onload = function() {
        var colors = ['blue', 'cyan', 'gold', 'grey', 'green'],
            h      = document.getElementById('heading1');
        h.style.color = colors[1];
      };     
    </script>
    <h1 id="heading1">hai</h1>
  </body>
</html>

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

2 Comments

Thank you dNitro! It actually works. But I am a little confused by the terms 'document.getElementById('heading') and 'h.style.color= colors[1]'. I am a beginner in javascript. So can you please expand these terms?
Have a look at this link: developer.mozilla.org/en-US/docs/Web/API/Document/…, It accidentaly also has an example of changing colors.
1

dNitro's solution works. I'm confused why you need to store colors in an array. If you want to provide different colors to different text. The common solution is design different color styles in css and use it in your element. As the code below

  <!doctype html>
    <html>
    <style media="screen">
      .cyan
      {
        color: cyan;
      }
      .blue
      {
        color: blue;
      }
    </style>
    <body>    
      <h1 class="cyan">Hello, </h1>
      <h1 class="blue">World</h1>
    </body>
    </html>

1 Comment

Thank you Allen4Tech. Yeah! I am familiar with the standard practice of assigning colors that you have mentioned. I am just trying to figure out a way to loop around certain colors and produce texts of them. :-)

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.