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

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.

Example:

Input: 10

Output:

<ul>
  <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>
</ul>

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;
}
console.log(printNums(10));

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

document.body.innerHTML=printNums(10);

 

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">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script src="yourjsfile.js"></script>
<script>
    let html = printNums(20);
    document.body.innerHTML = html;
</script>
</body>
</html>

and this is how the numbers look like in HTML:

output of colorful numbers javascript task

answered by user hues
...