0

I am trying to do something with JS but as per usual arrays prove to be the bane of my existence...

I have to loop through the numbers from 1 to 100 and print them in the HTML, every number that divides by 3 should show in the colour red while all other numbers should be black. I tried so many things and tried to find how to do it but could not figure it out. Could anyone, please, tell me what is the proper way to do it?

3
  • 2
    Before the post get's bombarded with dislikes can you post your code? Commented Jan 24, 2019 at 23:30
  • Is the question about colors? Modulo? Both? Neither? Commented Jan 24, 2019 at 23:33
  • Yes, sorry it's supposed to come in the colour red , not change to word. Commented Jan 24, 2019 at 23:38

3 Answers 3

1

You can use the following code to get what you are looking for.

for (let i = 1; i < 101; i++) {
    if(i % 3 == 0) {
       console.log('THREE');
    } else {
       console.log(i)
    }

}

If you need to write the values to a document, change the console.log to document.write

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

Comments

0

Put the THREE in some inline element and add css rule to change the color. For printing the list the solution explained by Jack. (Did it differently because I could.)

const text = (new Array(100))
	.fill('')
	.map((_v, i) => (i % 3) === 0 ? `<b>THREE</b>` : i)
	.join('<br/>');

document.write(`<p>${text}</p>`)
b {
  color: red;
}

Comments

0

First, loop through the numbers 1 to 100:

for (var i = 1; i <= 100; i++) {
    //Stuff will go here
}

Then, write the number i to HTML:

document.write(i);

Finally, add the if statement:

if (i % 3) {
    document.write(i);
} else {
    document.write("THREE");
}

Full code:

for (var i = 1; i <= 100; i++) {
  if (i % 3) {
    document.write(i + "<br>");
  } else {
    document.write("THREE<br>");
  }
}

EDIT

Here's how you'd make THREE red:

for (var i = 1; i <= 100; i++) {
  if (i % 3) {
    document.write(i + "<br>");
  } else {
    document.write("<span style='color: red;'>THREE</span><br>");
  }
}

3 Comments

Thank you for your answer, Jack Bashford, however, due to the late hour got quite distracted and asked the wrong question. I was thinking about the first task, which was to change the word , which I already did. What I was wandering now is how to change the colour of the text in the html.
What are the colours you want? Do you want, for example, blue for numbers and red for THREE? Could you please edit your question?
Just changing the THREE to red so I can see how it's done will be great thank you. I already edited the question :)

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.