I am new to DOM and JavaScript. I am still learning.
I’m trying to figure out how to add each element of an array to the html paragraph using innerHTML. I would like to see a different word each time I click on a button. I tried using forEach() or for loop methods, but none of those seem to work. Maybe, I’m doing it wrong. Do you have any suggestions? Math.random() works, but I do not want to use it.
Here’s my example:
const paragraph = document.getElementById('paragraph');
const button = document.getElementById('button');
const array = ['fun', 'smart', 'cool', 'guru', 'geek'];
const funcHandler = () => {
for(let i = 0; i < array.length; i++){
paragraph.innerHTML= array[i];
}
}
button.addEventListener('click', funcHandler);
2
Answers
Since you don’t want to use
Math.random()
seems like you’d want to instead cycle trough your array words. You can use the JS’s Remainder operator%
in order to loop-back to the array’s index0
item (word) once a currenti
integer reaches thearray.length
Or instead of
i += 1; i %= total;
you can use the shorteri = ++i % total;
In your current code, you’re iterating over the array inside the event handler, but you’re setting the innerHTML of the paragraph to each element of the array in succession. As a result, only the last element will be visible because each iteration overwrites the previous one.
To display a different word from the array each time you click the button, you can maintain an index variable to keep track of the current word to display.
Here is how I did it:
I used a "currentIndex" variable that initially points to the first element in the array. Each time the button is clicked, the current word at the "currentIndex" is displayed in the paragraph using "innerHTML". The "currentIndex" is then incremented, and the modulus operator "%" ensures that the index wraps back to 0 when it reaches the length of the array. This way, you cycle through the array of elements with each button click.
Make sure to adjust the element IDs in the code to match your HTML structure.