By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Colorful Numbers - JavaScript with HTML Task

+3 votes

Write JS (JavaScript) function to print the numbers from 1 to n.

Return a string holding HTML list with the odd lines in blue and even lines in green. See the example for more information.

The input comes as a single number argument n.


Input: 10


  <li><span style='color:green'>1</span></li>
  <li><span style='color:blue'>2</span></li>
  <li><span style='color:green'>3</span></li>
  <li><span style='color:blue'>4</span></li>
  <li><span style='color:green'>5</span></li>
  <li><span style='color:blue'>6</span></li>
  <li><span style='color:green'>7</span></li>
  <li><span style='color:blue'>8</span></li>
  <li><span style='color:green'>9</span></li>
  <li><span style='color:blue'>10</span></li>

The output should be returned as a result of your function in the form of a string.

asked in JavaScript category by user eiorgert
edited by user golearnweb

2 Answers

+2 votes

Here the JavaScript function itself - you can add it in your HTML - need to create it and connect with the js code:

function printNums(n) {
    let html = "<ul>\n";
    for (let i = 1; i <= n; i++) {
        let color = (i % 2 == 0) ? "blue" : "green";//checking the number if it is even or odd line with ternary operator
        html += `\t<li><span style="color:${color}">${i}</span></li>\n`;
    html += "</ul>\n";
    return html;

If you need to check it in Chrome put this in the console (F12):



answered by user golearnweb
Thnks! will create the html file and post it later
+1 vote

And here is the promised HTML fie wich connects to the script:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
<script src="yourjsfile.js"></script>
    let html = printNums(20);
    document.body.innerHTML = html;

and this is how the numbers look like in HTML:

output of colorful numbers javascript task

answered by user hues