Hey All,
I've just started out with JavaScript and was trying to play around with modifying & printing to the DOM.
My aim was to print the numbers 1 - 100 with a description after explaining if they were even or odd.
I.e.
The number 1 is odd
The number 2 is even
The number 3 is odd
.
.
.
The number 100 is even
This is what I've been trying:
const numberDiv = document.querySelector('div#numberDiv');
const numberArray = [];
for ( let i = 1; i <= 100; i++ ) {
if ( i % 2 == 0 ) {
numberArray.push(`<p>The number ${i} is even</p>`);
} else {
numberArray.push(`<p>The number ${i} is odd</p>`);
}
}
numberDiv.innerHTML = numberArray;
The best way I have found so far is to push the value on each loop to an array and then print the entire array. However, it's now printing a comma on a separate line, like so:
The number 1 is odd
,
The number 2 is even
,
The number 3 is odd
etc.
I know array items are separated by a comma within the array, but thought that they weren't shown when the array was printed -- as normally you'd have to use the .join(', ') method to include the comma.
The two main questions I have are:
1) What would be the best solution to this problem?
2) What's going wrong with my code?
Thanks in advance.
✌️
Top comments (3)
Based on your current code, the easiest thing to do would be to modify this line
to
Also, the reason the comma appears under your paragraph with spacing is because the paragraph element’s style for
display
isblock
. The comma is just a text node in the DOM.In terms of the best way to do this, updating
innerHTML
With a joined array seems fine.Hope that helps!
Ahhh awesome! Got it all working now, thanks for your help!
N.B. There was a small error in your code above, just an apostrophe and a back tick in the brackets, as opposed to two apostrophes. - I wasn't sure if you were trying to catch me out 😂.
Thanks again Nick, much appreciated!
Ah, I was on mobile. I must have picked the wrong one when closing the empty string. Glad it’s all sorted.